实现说明
unknown 吸收联合,never 消除联合可以归结为函数 assertNever、area。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件在加载时定义 assertNever、area。
签名一览:function assertNever(value: never)
核心语句
return Math.PI * shape.radius ** 2;
return shape.side ** 2;
代码示例
// unknown absorbs unions: string | unknown collapses to unknown
type Widened = string | unknown; // unknown
// never vanishes from unions and erases intersections
type KeptA = string | never; // string
type KeptB = string & unknown; // string
type Erased = string & never; // never
declare function assertNever(value: never): void;
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
default: {
// shape is narrowed to never here; adding a variant breaks this line
const exhausted: never = shape;
assertNever(exhausted);
return exhausted;
}
}
}
console.log(area({ kind: 'circle', radius: 2 }).toFixed(2));
console.log(area({ kind: 'square', side: 3 }));
// unknown accepts any initializer; KeptA stays string-only
const widened: Widened = 42;
const keptA: KeptA = 'still a string';
console.log(widened, keptA, keptA.length);