本示例使用console.log
测试推断类型。console.log
不太关心它的参数类型,因此两种情况都没有错误。
如果测试需要更具体的类型,结果会有所不同:
// Altered getShapes function
function getShapes() {
const result = [
{ kind: "circle", radius: 100 },
{ kind: "square", sideLength: 50 },
];
return result;
}
for (const shape of getShapes()) {
if (shape.kind === "circle") {
const radius: number = shape.radius;
} else {
const length: number = shape.sideLength;
}
}
With --strictNullChecks
打开,你会得到两个错误:
t.ts:25:11 - error TS2322: Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.
25 const radius: number = shape.radius;
~~~~~~
t.ts:29:11 - error TS2322: Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.
29 const length: number = shape.sideLength;
~~~~~~
正如该功能所宣传的那样,当as const
断言用于使编译器推断出精确的类型。
作为参考,这里是为返回类型推断的类型getShapes()
with const
宣言:
( { kind: string; radius: number; sideLength?: undefined; }
|{ kind: string; sideLength: number; radius?: undefined; } ) []
如你看到的,kind
被扩大到string
,并且数组元素类型是一个包含声明了所有属性的元素的联合,在某些联合成员中只有其中一些是可选的 - 这就是为什么当您进行日志记录时,控制台日志中不会出现错误shape.radius
- console.log
会很高兴地记录undefined
如果工会成员的类型错误。
这是为返回类型推断的类型getShapes()
with as const
断言:
readonly [
{ readonly kind: "circle"; readonly radius: 100; },
{ readonly kind: "square"; readonly sideLength: 50; }
]
现在它是只读元组类型,而不是数组,并且每个元组成员都有精确的类型(并且kind
正如预期的那样,是正确的文字类型)。