小编ars*_*eyr的帖子

防止条件分支中的 Typescript 缩小

在进行控制流分析时,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)

我假设 的类型aFoo | 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

5
推荐指数
1
解决办法
297
查看次数

标签 统计

typescript ×1