首页 文章

在typescript中指定union类型

提问于
浏览
2

我有这样的事情:

interface ISome {
    myValue: number | string;
    // some more members
}

我有一个函数,它将接受 ISome ,其 myValue 是一个数字,并使用它像:

function (some: ISome): number { // I accept only ISome with myValue type number
    return some.myValue + 3;
}

打字稿编译器按预期抱怨,因为 some.myValue 是数字或字符串 . 当然我可以使用union类型来检查:

function (some: ISome): number { // I could use a guard
    if (typeof some.myValue === "number") {
        return some.myValue + 3;
    }
}

但这不是我想要的,因为我经常需要这样做 .

1 回答

  • 2

    您可以使用交集类型覆盖union类型,并在那里指定 myValue 的类型:

    function someFunction(some: ISome & {  
        myValue: number
    }): number {
        return some.myValue + 3; // No error
    }
    

相关问题