简体   繁体   English

打字稿中的覆盖函数返回类型

[英]Override function return type in typescript

Is there a way to override a function's return type? 有没有办法覆盖函数的返回类型? Using typescript 3.1.6 at the time of writing. 在撰写本文时使用typescript 3.1.6

Contrived example, but to get the point across: 有争议的例子,但要明白:

function sample(foo): string | number {
    if (foo === 'foo') {
        return 'string'
    }

    return 1
}

const result = sample('bar')

// but since we know it's a number we should be able to tell typescript this
const typedResult: number = sample('bar')

In reality, the logic in the function might be complex. 实际上,函数中的逻辑可能很复杂。

keyof and lookup types looked promising, but I'm not working with a limited set of options nor can I deduce a pattern reliably. keyof和lookup类型看起来很有前途,但我不是在使用有限的选项集,也不能可靠地推断出模式。

I've also tried the following workaround, but it didn't work. 我也尝试了以下解决方法,但它没有用。 It seems like you can't override a type. 看起来你无法覆盖一个类型。

const result = sample('bar')
const typedResult: number = result

What's frustrating about this is that even if I do the proper checks to accurately check what type I'm dealing with, I still get type errors if I use methods exclusive to that type. 令人沮丧的是,即使我进行了正确的检查以准确检查我正在处理的类型,如果我使用该类型的独有方法,我仍会遇到类型错误。 Typescript still thinks we don't 100% know the type. 打字稿仍然认为我们不是100%知道这种类型。

Any leads or solutions to this? 这个的任何线索或解决方案?

For that you'd use a type assertion : 为此你要使用一个类型断言

const typedResult = sample('bar') as number

That said, it may be worth separating sample into three functions: 也就是说,将sample分成三个函数可能是值得的:

  • One that always returns a number 一个总是返回一个数字
  • One that always returns a string 一个总是返回一个字符串
  • One that does what sample does in your question (having it do the relevant parameter test and then hand off to one of the other two functions) 在你的问题中做一个sample做的事情(让它做相关的参数测试,然后交给另外两个函数)

...so that when you know what type your result will be, you can use one of the first two and not use a type assertion. ...这样当你知道你的结果是什么类型时,你可以使用前两个中的一个而不使用类型断言。

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

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