如何在 Typescript 中选择特定的 return 类型?

How to pick a particular return type in Typescript?

假设函数的 return 类型是 a | b。现在,如果我知道 return 类型对于特定调用肯定是 a,我如何告诉打字稿将 returned 值视为 a。通常,如果我尝试这样做:

const x: a = func();

我得到type a | b is not assignable to type a

只需转换 return 类型:

const x: a = <a>func();

通过这种方式,您可以告诉打字稿您确定知道 return 类型是什么。


另一种方法是像这样为函数创建重载:

function func(): a;

然后像原来那样调用它

const x: a = func();

转换您感兴趣的特定值当然是一个有效的选择,但它基于一个只有您(程序员)知道的隐藏假设。如果 6 个月后您更改了函数的行为,导致您的假设不再有效,您将收到运行时错误。

更稳健的解决方案是通过类型系统对程序中的假设进行编码,通过重载或条件类型。

例如:

function f1(x: string): number | string {
    return undefined;
}

const a1: number = f1('foo') // wrong, can't do

function f2(x: string): string
function f2(): number
function f2(x?: string): number | string {
    return undefined;
}

const a2s: string = f2('foo') // OK
const a2n: number = f2() // OK

同样,条件类型允许你表达同样的事情:

function f3<T>(x?: T): T extends string ? string : number {
    return undefined;
}

const a3s: string = f3('foo') // OK
const a3n: number = f3()

Playground