在进行控制流分析时,Typescript 似乎正在缩小联合范围:
type Foo = {x: number}
type Bar = {x: number, y: string}
function f(arg: Foo | Bar) {
// Type of a is Foo | null
const a = true ? arg : null
}
Run Code Online (Sandbox Code Playgroud)
我假设 的类型a是Foo | null因为Foo是 的子类型Bar,所以是这里的最小安全类型。如何防止这种缩小的情况发生?例如,如果我想做以下事情该怎么办:
function p(arr: (Foo | Bar)[]) {
const b = arr.length ? arr[0] : null;
// Treat b as Foo | Bar | null
if (b && 'y' in b) { …Run Code Online (Sandbox Code Playgroud) typescript ×1