首页 > 解决方案 > 打字稿不能正确推断类型

问题描述

class A {
    readonly is_prop: boolean;
    constructor(is_prop: boolean) {
        this.is_prop = is_prop;
    }
}

class B {
    readonly my_prop: boolean;
    constructor(my_prop: boolean) {
        this.my_prop = my_prop;
    }
}

type A1 = A & {is_prop: true};
type A2 = A & {is_prop: false};

type C = A1 | A2 | B;

const a: A = new A(true);
const b: A = new A(false);
const c: B = new B(true);

const e: A1 | null = a.is_prop ? a : null;

在上面的例子中,为什么赋值e给错误?为什么 TS 不推断这is_prop将是真的

打字稿游乐场

标签: typescripttypescript-typings

解决方案


错误是因为a是类型A

const a: A = new A(true);

在三元中,您检查is_propis true,但变量a仍然是 类型A。该属性已缩小到true,但a没有更改类型。例如,根据您的缩小范围,此代码将是有效的:

const trueVal: true | null = a.is_prop ? a.is_prop : null 

如果您希望能够缩小 的类型a,则需要通过声明它是联合来说明它可以是多种类型之一:

const a: A1|A2 = new A(true);

有更多选择的游乐场。


推荐阅读