对多个基元类型的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);
}