1

I expect the following code to not compile. The reason is that when assigning person and expert to people, the person constant satisfies the type for the people constant which should be Person type. However, the expert has a skills filed that doesn't exist on Person type.

Yet it does compile.

interface Person {
  name: string;
  age?: number; 
}

interface Developer {
  name: string;
  age?: number;
  skills: string[];
}

const person: Person = {
  name: 'john doe',
  age: 20,
};

const expert: Developer = {
  name: 'jane doe',
  skills: ['javascript', 'react']
};

const people: Person[] = [ person, expert ];

console.log(people);

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    `Developer` is structurally a sub type of `Person`. Any `Developer` is a `Person` so you can assign a developer where a person is expected. This is a fundamental tenant of OOP. (The exception to this in TS is excess property checks, but it only kicks in on fresh object literals) – Titian Cernicova-Dragomir Jun 17 '20 at 06:41
  • Does this answer your question? [Why does TypeScript not throw an error when the function argument type is mismatched?](https://stackoverflow.com/questions/61841687/why-does-typescript-not-throw-an-error-when-the-function-argument-type-is-mismat) – VLAZ Jun 17 '20 at 06:44
  • Also relevant: [Empty interface allow any object?](https://stackoverflow.com/q/42537727) | [Why can I avoid excess property check in typescript just by passing a reference to an object to a function rather than the object in its literal form?](https://stackoverflow.com/q/52852278) | [Why does TypeScript not throw an error when the function argument type is mismatched?](https://stackoverflow.com/q/61841687) | [Typescript: prevent assignment of object with more properties than is specified in target interface](https://stackoverflow.com/q/57497299) – VLAZ Jun 17 '20 at 06:47

0 Answers0