I recently came across this weird behavior (imo) in TypeScript. At compile time, it will complain about redundant properties only if the expected type of the variable is an interface, if the interface does not have required fields. Link to TypeScript Playground No. 1: http://goo.gl/rnsLjd
interface IAnimal {
name?: string;
}
class Animal implements IAnimal {
}
var x : IAnimal = { bar: true };
var y : Animal = { bar: true };
function foo<T>(t: T) {
}
foo<IAnimal>({ bar: true });
foo<Animal>({ bar: true });
Now, if you add a “required” field to the IAnimal interface and implement it in the Animal class, it will start complaining about the “bar”, which is a redundant property for bot interfaces and classes. Link to TypeScript Playground No. 2: http://goo.gl/9wEKvp
interface IAnimal {
name?: string;
mandatory: number;
}
class Animal implements IAnimal {
mandatory: number;
}
var x : IAnimal = { mandatory: 0, bar: true }; // Object literal may only specify known properties, and 'bar' does not exist in type 'IAnimal'
var y : Animal = { mandatory: 0, bar: true }; // Not fine anymore.. why? Object literal may only specify known properties, and 'bar' does not exist in type 'Animal'
function foo<T>(t: T) {
}
foo<IAnimal>({ mandatory: 0, bar: true }); // Object literal may only specify known properties, and 'bar' does not exist in type 'IAnimal'
foo<Animal>({ mandatory: 0,bar: true }); // Not fine anymore.. why? Object literal may only specify known properties, and 'bar' does not exist in type 'Animal'
- , , , .
, .