繁体   English   中英

如何让 typescript 根据参数返回正确的类型

[英]How to let typescript return correct type based on parameters

我有这样的代码示例

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'
    }
  }
}

所以你可以看到我有一个 function test(c:boolean) ,它接受一个 boolean 并给出相应的返回 object。

问题是当我使用这个 function 时,它有错误

let a = test(true).radio;

Typescript 在这一行告诉我这个错误:

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

如您所见,根据逻辑( c is true) ,这行代码是正确的,我怎么能告诉 typescript 这个? 或者有没有其他方法可以实现这一点。 谢谢

您需要重载 function以获得所需的行为,如下所示:

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

TSPlayground 链接

类似于 Nishant 的答案,但使用通用

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

let a = test(true).radio;

暂无
暂无

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

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