简体   繁体   中英

How to let typescript return correct type based on parameters

i'm having a code example like this

interface BaseQuestionType {
  label?: string
}
export type RadioQuestionType = BaseQuestionType & {
  radio: boolean
}
export type TextQuestionType = BaseQuestionType & {
  text: string
}

function test(c: boolean): (RadioQuestionType | TextQuestionType){

  if (c) {
    return {
      radio: true
    }
  } else {
    return {
      text: '11'
    }
  }
}

So you can see i have a function test(c:boolean) that takes in a boolean and give the corresponding return object.

The problem is when i use this function, it has error

let a = test(true).radio;

Typescript told me this error in this line:

Property 'radio' does not exist on type 'RadioQuestionType | TextQuestionType'.
  Property 'radio' does not exist on type 'TextQuestionType'.(2339)

As you see, according to the logic ( c is true) , this line of code is correct, how can i tell typescript this? Or is there any other way to implement this. Thanks

You need to overload your function to get the desired behaviour like this:

function test(c: true):RadioQuestionType;
function test(c: false):TextQuestionType;
function test(c: boolean): (RadioQuestionType | TextQuestionType){

TSPlayground Link

Similar to Nishant's answer, but using generic :

function test<T extends boolean>(c: T): T extends true ? RadioQuestionType : TextQuestionType;
function test(c: boolean): (RadioQuestionType | TextQuestionType){
   ...
}

let a = test(true).radio;

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