相关疑难解决方法(0)

打字稿:接口与类型

这些语句(接口与类型)之间有什么区别?

interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};
Run Code Online (Sandbox Code Playgroud)

typescript

516
推荐指数
16
解决办法
9万
查看次数

为 Record<string, string> 分配接口或类型的打字稿

在阅读了这个问题这篇文章后,我仍然对 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

5
推荐指数
1
解决办法
493
查看次数

标签 统计

typescript ×2