Typescript:如何表达一个泛型函数,其中类型被限制为几种类型之一 [英] Typescript: How to express a generic function where the type is restricted to one of several types
问题描述
尝试1:
函数add(a:string | number ,b:string | number){
return a + b;
}
这是行不通的,因为a和b的类型可能不匹配;因此产生的错误是有意义的:错误TS2365:运算符'+'不能应用于类型的字符串|数字'和'字符串|数字'。
尝试2:
函数add< T扩展字符串|数字>(a:T,b:T){
返回a + b;
}
这将返回相同的错误代码:错误TS2365:运算符'+'不能用于类型'T'和'T'。
尝试3:
函数add(a:string,b:string):string;
function add(a:number,b:number):number;
function add(a:any,b:any){
return a + b;
$ b $ p
$ b 这个(函数重载)可以正常工作,但看起来像是过度杀伤。有没有更优雅的方式来表达这一点? 3像这样:
函数add< T extends string | (a:T,b:T):T;
function add(a:any,b:any){
return a + b;
}
然后您可以像这样使用它:
//返回类型是`number`
add(1,2);
//返回类型是`string`
add('1','2');
add< number>(1,2);
add< string>('1','2');
...这些会导致类型错误:
add(1,'2');
add< number>('1','2');
add< string>(1,2);
add(true,false);
但是,如果您不打算使用输入类型,那么我会坚持使用函数重载。在我看来最容易理解。
For example if a method that adds two arguments, a and b, where they should be of the same type and that type should be either a string or a number.
Attempt 1:
function add(a: string | number, b: string | number) {
return a + b;
}
This won't work because the types of a and b may not match; so the resulting error makes sense: error TS2365: Operator '+' cannot be applied to types 'string | number' and 'string | number'.
Attempt 2:
function add<T extends string | number>(a: T, b: T) {
return a + b;
}
This returns the same error code: error TS2365: Operator '+' cannot be applied to types 'T' and 'T'.
Attempt 3:
function add(a: string, b: string): string;
function add(a: number, b: number): number;
function add(a: any, b: any) {
return a + b;
}
This (function overloading) works properly, but seems like overkill. Is there a more elegant way to express this?
解决方案 You can also combine your attempts 2 & 3 like this:
function add<T extends string | number>(a: T, b: T): T;
function add(a: any, b: any) {
return a + b;
}
Then you can use it like this:
// Return type is `number`
add(1, 2);
// Return type is `string`
add('1', '2');
add<number>(1, 2);
add<string>('1', '2');
... and these cause type errors as expected:
add(1, '2');
add<number>('1', '2');
add<string>(1, 2);
add(true, false);
However, if you're not going to use the input type, then I would stick with just function overloads. Easiest to understand in my opinion.
这篇关于Typescript:如何表达一个泛型函数,其中类型被限制为几种类型之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!