[英]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.所以你可以看到我有一个 function test(c:boolean)
,它接受一个 boolean 并给出相应的返回 object。
The problem is when i use this function, it has error问题是当我使用这个 function 时,它有错误
let a = test(true).radio;
Typescript told me this error in this line: Typescript 在这一行告诉我这个错误:
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?如您所见,根据逻辑( c is true)
,这行代码是正确的,我怎么能告诉 typescript 这个? Or is there any other way to implement this.或者有没有其他方法可以实现这一点。 Thanks谢谢
You need to overload your function to get the desired behaviour like this:您需要重载 function以获得所需的行为,如下所示:
function test(c: true):RadioQuestionType;
function test(c: false):TextQuestionType;
function test(c: boolean): (RadioQuestionType | TextQuestionType){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.