TypeScript 中的这些语句( interface
vs type
)有什么区别?
interface X {
a: number
b: string
}
type X = {
a: number
b: string
};
原文由 user6101582 发布,翻译遵循 CC BY-SA 4.0 许可协议
TypeScript 中的这些语句( interface
vs type
)有什么区别?
interface X {
a: number
b: string
}
type X = {
a: number
b: string
};
原文由 user6101582 发布,翻译遵循 CC BY-SA 4.0 许可协议
想加我的2美分;
我曾经是 “接口爱好者” (更喜欢 interface
到 type
除了联合、交叉点等)…… 直到 我开始使用“任何键值对象”类型又名 Record<string, unknown>
如果您键入“任何键值对象”:
function foo(data: Record<string, unknown>): void {
for (const [key, value] of Object.entries(data)) {
// whatever
}
}
如果你使用 interface
你可能会走到死胡同
interface IGoo {
iam: string;
}
function getGoo(): IGoo {
return { iam: 'an interface' };
}
const goo = getGoo();
foo(goo); // ERROR
// Argument of type 'IGoo' is not assignable to parameter of type
// 'Record<string, unknown>'.
// Index signature for type 'string' is missing in type
// 'IGoo'.ts(2345)
而 type
就像一个魅力:
type Hoo = {
iam: string;
};
function getHoo(): Hoo {
return { iam: 'a type' };
}
const hoo = getHoo();
foo(hoo); // works
这个特殊的用例 - IMO - 有所作为。
原文由 Manu Artero 发布,翻译遵循 CC BY-SA 4.0 许可协议
2021 年 3 月更新:较新的 TypeScript 手册(在下面的 nju-clc 答案中 也提到过)有一节 Interfaces vs. Type Aliases 解释了差异。
原始答案(2016)
根据 (现已存档)TypeScript 语言规范:
该规范继续提到: