首页 > 解决方案 > 基于参数属性的打字稿函数返回类型

问题描述

如何为函数创建正确的类型,以便根据其输入参数的属性,在调用此函数时获得正确的返回类型?

这是我目前得到的,但两个电话都给了我相同的boolean | boolean[]类型 when fn({ a: 42 })should give mebooleanfn({ b: 'hi' })should give me boolean[]

type ParamType = { a?: number, b?: string }
type ReturnType<T> =
    T extends 'a' ? boolean :
    T extends 'b' ? boolean[] :
    never[]

function fn<T extends keyof ParamType>(arg: ParamType) {
    if (arg.a) {
        return true as ReturnType<T>;
    }
    else if (arg.b) {
        return [true, false] as ReturnType<T>;
    }
    else return [] as ReturnType<T>;
}

fn({ a: 42 });      //  function fn<"a" | "b">(arg: ParamType ): boolean | boolean[]
fn({ b: 'hi' });    //  function fn<"a" | "b">(arg: ParamType ): boolean | boolean[]

a另外,我不是必须在类型中定义文字对象属性和两次的超级粉丝b,如果有更好的方法来做到这一点,请指出正确的方向。

标签: typescriptfunctiongenericsparameters

解决方案


您的问题很不寻常,但首先:使用in运算符检查密钥是否存在。其次:如果 a 和 b 都被声明,即使是可选的,这也没有效果。使用联合。最后,如果你声明的类型参数没有分配给参数,在大多数情况下,它是没有效果的。

尝试这个:

type ParamType = {a: number | string;} | {b: number | string;};
type MyReturnType<T> =
    T extends 'a' ? boolean :
    T extends 'b' ? boolean[] :
    never[];

function fn<T extends ParamType>(arg: T) {
    if ("a" in arg) {
        return true as MyReturnType<keyof T>;
    }
    else if ("b" in arg) {
        return [true, false] as MyReturnType<keyof T>;
    }
    else return [] as MyReturnType<keyof T>;
}

fn({a: 42}); 
/*function fn<{
    a: number;
}>(arg: {
    a: number;
}): boolean*/
fn({b: 'hi'});
/*function fn<{
    b: string;
}>(arg: {
    b: string;
}): boolean[]*/

有关工会,请参阅https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#unions和https://www.typescriptlang.org/docs/handbook/release-notes/ typescript-2-7.html#type-guards-inferred-from-in-operator用于in类型保护。


推荐阅读