Jake Lam
Jake Lam

Reputation: 3452

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

Upvotes: 0

Views: 71

Answers (2)

Owl
Owl

Reputation: 6853

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;

Upvotes: 1

Nishant
Nishant

Reputation: 55866

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

Upvotes: 1

Related Questions