我最近偶然发现了TypeScript中这种奇怪的(imo)行为。 在编译过程中,只有当接口没有必填字段时,期望变量的类型是一个接口,它才会抱怨超额属性。链接打字稿游乐场#1:http://goo.gl/rnsLjdTypeScript在接口和类中处理多余属性的区别
interface IAnimal {
name?: string;
}
class Animal implements IAnimal {
}
var x : IAnimal = { bar: true }; // Object literal may only specify known properties, and 'bar' does not exist in type 'IAnimal'
var y : Animal = { bar: true }; // Just fine.. why?
function foo<T>(t: T) {
}
foo<IAnimal>({ bar: true }); // Object literal may only specify known properties, and 'bar' does not exist in type 'IAnimal'
foo<Animal>({ bar: true }); // Just fine.. why?
现在,如果你是“强制性”字段添加到IAnimal接口,并在动物类会开始抱怨“巴”是为机器人过量财产实现它接口和类。链接打字稿游乐场#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'
如果任何人有一些见解,为什么这工作,因为它不请做。
我对此很好奇。从pull request
关于该功能的深入信息:https://gitter.im/Microsoft/TypeScript?at=56419a856420c33467a0fbb7(来自微软贡献者)。 –