问题
考虑一下下面的TypeScript代码。
interface Person {
first: string;
last: string;
}
const personKeys = [
'first',
'last',
] as const;
personKeys 列出了Person 的属性键。我们能否在编译时检查这个列表是否正确?
解决方案
import {assert as tsafeAssert, Equals} from 'tsafe';
tsafeAssert<Equals<
keyof Person,
(typeof personKeys)[number]
>>();
库tsafe,使我们能够检查两个类型是否相等。
Equals<> 的参数的计算方法如下:
// %inferred-type: "first" | "last"
type A = keyof Person;
// %inferred-type: readonly ["first", "last"]
type B = typeof personKeys;
// %inferred-type: "first" | "last"
type C = B[number];
为了计算类型C ,我们正在使用索引访问运算符T[K] :对于一个给定的类型T ,它计算所有属性的类型,其键可分配给类型K 。以下两种类型大致上是等价的。这解释了计算B[number] 的结果。
type T = ["first", "last"];
type U = {
0: "first",
1: "last",
};