![](/img/trans.png)
[英]How to define the return type of a function according to the input parameters with Typescript?
[英]How to define return type based on the parameters in typescript
我正在创建一个boolean
如果参数为true
则返回 boolean ,并返回boolean | undefined
如果参数为false
则boolean | undefined
。 我尝试使用conditional types
或overloaded functions
,但都不起作用,有人能帮忙吗? 谢谢!
// first try using conditional type
const getData = <T extends boolean>(mandantory: T): T extends true ? boolean : (boolean | undefined) => {
return mandantory ? false : undefined // Type 'undefined' is not assignable to type 'T extends true ? boolean : boolean | undefined'.(2322)
}
// second try using overload functions
type GetData ={
(mandantory: true):boolean;
(mandantory: false): boolean | undefined
}
const getData1:GetData = (mandantory: boolean) => { // Type 'undefined' is not assignable to type 'boolean'.(2322)
return mandantory ? false: undefined
}
您可以使用function
语法编写它,如下所示:
function getData(mandatory: true): false;
function getData(mandatory: false): boolean | undefined;
function getData(mandatory: boolean): boolean | undefined {
if (mandatory) {
return false;
}
return undefined;
}
用类型和箭头 function 编写它,如果不通过类型断言应用类型,而不仅仅是键入const
,我无法让它工作:
interface GetData {
(mandatory: true): false;
(mandatory: false): boolean | undefined;
}
const getData = ((mandatory: boolean): boolean | undefined => {
if (mandatory) {
return false;
}
return undefined;
}) as GetData;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.