【发布时间】:2018-12-11 07:03:27
【问题描述】:
在定义接口时,TypeScript 文档提到,只要对象采用接口的形状,任何多余的对象属性都是允许的。
一个例子
interface Person {
name: string
}
function print(somebody: Person) {
console.log(somebody.name);
}
let obj = { name: "Johnny", additionalProps: true }
print(obj); // this is okay
但这仅适用于函数参数吗?下面我尝试创建一个转换为特定类型的对象,并且仅当我不使用花括号时,添加其他属性才会引发错误。
interface Animal {
name: string;
}
let myDog = <Animal> {
name: "Spot",
altProperty: "anything" // no error
};
myDog.altProperty = "anything else"; // Property 'altProperty' does not exist on type 'Animal'
似乎您可以在声明对象类型时为其分配任意数量的属性,但您无法访问其中任何一个,因为它们不在类型定义中。这是为什么呢?
【问题讨论】:
标签: typescript