繁体   English   中英

如何根据 typescript 中的参数定义返回类型

[英]How to define return type based on the parameters in typescript

我正在创建一个boolean如果参数为true则返回 boolean ,并返回boolean | undefined 如果参数为falseboolean | undefined 我尝试使用conditional typesoverloaded 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.

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