我最近偶然發現了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(來自微軟貢獻者)。 –