Javascript 如何让typescript根据参数返回正确的类型
我有一个这样的代码示例Javascript 如何让typescript根据参数返回正确的类型,javascript,typescript,Javascript,Typescript,我有一个这样的代码示例 interface BaseQuestionType { label?: string } export type RadioQuestionType = BaseQuestionType & { radio: boolean } export type TextQuestionType = BaseQuestionType & { text: string } function test(c: boolean): (RadioQuestio
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'
}
}
}
您可以看到我有一个函数test(c:boolean)
,它接受一个布尔值并给出相应的返回对象
问题是当我使用这个函数时,它有错误
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为true)
,这行代码是正确的,我如何才能告诉typescript这一点?或者是否有其他方法来实现这一点。
谢谢您需要获得以下所需的行为:
功能测试(c:true):RadioQuestionType;
功能测试(c:false):TextQuestionType;
功能测试(c:布尔值):(RadioQuestionType | TextQuestionType){
您需要获得如下所需的行为:
功能测试(c:true):RadioQuestionType;
功能测试(c:false):TextQuestionType;
功能测试(c:布尔值):(RadioQuestionType | TextQuestionType){
类似于Nishant的回答,但使用:
功能测试(c:T):T扩展true?RadioQuestionType:TextQuestionType;
功能测试(c:布尔值):(RadioQuestionType | TextQuestionType){
...
}
设a=测试(真)。无线电;
类似于Nishant的回答,但使用:
功能测试(c:T):T扩展true?RadioQuestionType:TextQuestionType;
功能测试(c:布尔值):(RadioQuestionType | TextQuestionType){
...
}
设a=测试(真)。无线电;
function test<T extends boolean>(c: T): T extends true ? RadioQuestionType : TextQuestionType;
function test(c: boolean): (RadioQuestionType | TextQuestionType){
...
}
let a = test(true).radio;