在阅读了这个问题或这篇文章后,我仍然对 aninterface和 a之间的细微差别感到有些困惑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
Run Code Online (Sandbox Code Playgroud)
使用 a 声明我的对象时可以进行赋值type,但使用interface. 它说缺少索引签名,但就我对索引签名的(有限)理解而言,没有一个MyType并且MyInterface实际上有一个。
最后一行没有编译而前一行编译的原因是什么?
typescript ×1