TypeScript条件返回值类型?

TypeScript条件返回值类型?

问题描述:

function f(x:boolean|string) { return x }
f(true) // boolean | string

为什么打字稿不能理解返回值是布尔值?

Why can't typescript understand that the return value is a boolean?

function f(x:boolean|string) {
    return typeof x === 'boolean' ? true : 'str'
}
f(true) // boolean | string

它也不明白.

我需要手动设置函数重载定义吗?

Do I need to manually setup a function overload definition?

Typescript不会基于函数中的类型保护来推断不同的返回类型.但是,您可以定义多个函数签名,以使编译器知道输入参数类型和结果类型之间的链接:

Typescript will not infer different return types based on type guards in the function. You can however define multiple function signatures for let the compiler know the links between input parameter types and result type:

function ff(x: boolean): boolean;
function ff(x: string): string;

// Implementation signature, not publicly visible
function ff(x: boolean | string): boolean | string {
    return typeof x === 'boolean' ? true : 'str'
}