为什么 Typescript 在接口上抛出错误,但在类型上却没有?

Dua*_*nnx 4 javascript typescript

我不知道为什么 Typescript 在使用接口时会抛出错误,但在类型上却可以正常工作。请考虑这段代码:

const fn = (a: { [key: string]: number | string }) => {
  console.log(a)
};

interface FooInterface {
  id: number;
  name: string;
}
type FooType = {
  id: number;
  name: string;
}

const fooInterface: FooInterface = { id: 1, name: 'name' };
const fooType: FooType = { id: 1, name: 'name' };

fn(fooType);
fn(fooInterface); <-- error here
Run Code Online (Sandbox Code Playgroud)

游乐场链接

Typescript 将抛出一行错误fn(fooInterface);。它说:

Argument of type 'FooInterface' is not assignable to parameter of type '{ [key: string]: string | number; }'.
Index signature for type 'string' is missing in type 'FooInterface'.
Run Code Online (Sandbox Code Playgroud)

为什么会发生错误,为什么只发生在接口上?

won*_*ame 5

接口没有隐式索引签名,这就是您无法传递接口的原因。如果您添加索引签名,错误就会消失:

interface FooInterface {
  id: number;
  name: string;
  [a: string]: string | number;
}
Run Code Online (Sandbox Code Playgroud)

这背后的原因是接口可以通过声明合并来增强,而类型则不可能。

相关问题:Typescript#15300