我不确定我的问题是否清楚,所以我会试着详细说明.
假设我有一个实现接口MyInterface
的类MyClass
.除了实现所需的属性(在本例中为myProp1
)外,它还有一个附加属性myProp2
,如下面的代码片段所示:
interface MyInterface {
myProp1: string;
}
class MyClass implements MyInterface {
myProp2 = '2';
constructor(public myProp1: string) {}
}
然后,在创建类的实例时,我将其类型指定为MyInterface
.即使instance
具有未在MyInterface
中指定的属性,TypeScrip也不会出现错误:
let instance: MyInterface = new MyClass('1'); // no type error
但是,当try 访问添加的属性(myProp2
)时,我收到一个错误:
console.log(instance.myProp2); // 'myProp2' does not exist on type 'MyInterface'. Did you mean 'myProp1'?
这是一个错误,还是这里的故意行为?