简体   繁体   English

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

[英]How to pick a particular return type in Typescript?

Lets say return type of a function is a | b假设 function 的返回类型是a | b a | b . a | b Now if I know that the return type will be a for sure for a particular call, how do I tell typescript to treat the returned value as a .现在,如果我知道特定调用的返回类型肯定是a ,我如何告诉 typescript 将返回值a . Normally if I try this:通常,如果我尝试这个:

const x: a = func();

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

Just cast the return type:只需转换返回类型:

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

In this way, you are telling typescript that you know for sure what the return type is.通过这种方式,您告诉 typescript 您确定返回类型是什么。


Another way to do it is to create an overload for the function like so:另一种方法是为 function 创建一个过载,如下所示:

function func(): a;

Then call it like you did originally然后像原来一样调用它

const x: a = func();

Casting the particular value you're interested in is certainly a valid option, but it's based on a hidden assumption that only you, the programmer, know about.铸造您感兴趣的特定值当然是一个有效的选择,但它基于一个只有您(程序员)知道的隐藏假设。 If 6 months down the line you change the behaviour of your function in such a way that your assumption is no longer valid, you'll get a runtime error.如果 6 个月后您更改了 function 的行为,使您的假设不再有效,您将收到运行时错误。

A more robust solution would be to encode your assumption in the program through the type system, either via overloading or via conditional types.一个更健壮的解决方案是通过类型系统在程序中编码您的假设,无论是通过重载还是通过条件类型。

For example:例如:

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

Similarly, conditional types allow you to express the same thing:类似地,条件类型允许你表达同样的事情:

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

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

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM