首页 > 解决方案 > 如何在 TypeScript 类方法中有条件地提示布尔返回类型?

问题描述

在以下代码示例中,我的目标是:

type A = { x: true };
type B = { x: false };

type AorB = A | B;

class MyClass<Input extends AorB> {
    _input: Input;

    constructor(input: Input) {
        this._input = input;
    }

    isX(): Input extends A ? true : false {
        return this._input.x;
    }
}

但我得到了Type 'boolean' is not assignable to type 'Input extends A ? true : false'.(2322)

打字稿游乐场:

https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDeUAeAuKwBOBXaAvgNwBQokUAQgsmpgGYCGANgM6GlnjQDCNcAHyqcAxs0atWUACIAeAKJQIqYBAB2AEyk8AfMhJRDUAPoRM8zkagiA9mtY5cI4DewAKM1HkBKfVavAABYAlqwAdKY0EKRWBCQGRqEAGm7e5koq6lqwUAD8WHjQDCzsfv6G2BDAuNhqWCHhpmGoMUZxBEA

标签: typescript

解决方案


这似乎有效:

    isX(): E["x"] {
        return this._e.x;
    }

游乐场链接


推荐阅读