Why is this example ok in Typescript:
class Person {
name: String;
age: number;
}
class Customer {
name: String;
}
const cust: Customer = new Person();
But not this example?
type Boj = {boj: number};
let b: Boj = {boj: 3, jj: 3};
Should not both work with a structual typesystem?
CodePudding user response:
The behavior in second example is called excess property checking
TypeScript takes the stance that there’s probably a bug in this code. Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error
This applies only to object literals. Assigning variable with extra properties is still allowed:
type Boj = { boj: number };
const foo = { boj: 3, jj: 3 }; // inferred type is { boj: number; jj: number; }
let b: Boj = foo; // no error here, foo is not object literal