Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对多个基元类型的TypeScript通用约束_Typescript - Fatal编程技术网

对多个基元类型的TypeScript通用约束

对多个基元类型的TypeScript通用约束,typescript,Typescript,鉴于此功能: myFunc(object: string | null): string | null {} 当对象为string时,我希望此函数的返回类型为string,当对象的返回类型为string | null时,此函数的返回类型为string | null 我试过: myFunc<T extends string | null>(object: T): T { return "returnValue"; //Type '"returnValue"' is not a

鉴于此功能:

myFunc(object: string | null): string | null {}
当对象为string时,我希望此函数的返回类型为string,当对象的返回类型为string | null时,此函数的返回类型为string | null

我试过:

myFunc<T extends string | null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}


两者都产生相同的编译错误。我还没有找到正确的语法来做这件事。

我真不敢相信我会建议重载,因为我花了大量时间解释如何避免大多数重载。。。但是重载将是一个很好的建模方法

class Example {
    myFunc(obj: string): string;
    myFunc(obj: string | null): string | null;
    myFunc(obj: string | null): string | null {
        return "returnValue";
    }
}

function test(a: string | null, b: string) {
    const example = new Example();

    // resultA: string | null
    const resultA = example.myFunc(a);

    // resultB: string
    const resultB = example.myFunc(b);
}
在上面的示例中,返回类型映射到输入类型,因此resultA和resultB具有预期的类型,前提是您在启用严格空检查的情况下运行

class Example {
    myFunc(obj: string): string;
    myFunc(obj: string | null): string | null;
    myFunc(obj: string | null): string | null {
        return "returnValue";
    }
}

function test(a: string | null, b: string) {
    const example = new Example();

    // resultA: string | null
    const resultA = example.myFunc(a);

    // resultB: string
    const resultB = example.myFunc(b);
}