简体   繁体   中英

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.

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.

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.

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:

  • 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)

...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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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