【发布时间】:2021-03-06 06:51:59
【问题描述】:
阅读this question 或this article 后,我仍然对interface 和type 之间的细微差别感到有些困惑。
在本例中,我的目标是将一个简单对象分配给更广泛的Record<string, string> 类型:
interface MyInterface {
foobar: string;
}
type MyType = {
foobar: string;
}
const exampleInterface: MyInterface = { foobar: 'hello world' };
const exampleType: MyType = { foobar: 'hello world' };
let record: Record<string, string> = {};
record = exampleType; // Compiles
record = exampleInterface; // Index signature is missing
使用type 声明我的对象时可以进行赋值,但使用interface 声明类似的对象时则不能。它说缺少索引签名,但根据我对索引签名的(有限)理解,MyType 和 MyInterface 实际上都没有。
最后一行不编译而上一行编译的原因是什么?
【问题讨论】:
-
有趣。我没有意识到这一点,但它确实是有道理的。
{ foobar: string }类型是您可以接收的下限。它基本上意味着“任何具有至少键foobar的对象”。显然,制作成一种类型保留了这种意义。但是,对于 interface 而言,语义是不同的,它可能没有任何其他键。这有点奇怪,因为这两个变量都不会接受要添加的名为hello的新密钥。所以它们的可分配性不同。
标签: typescript