泛型类型(T)与打字稿中的任何类型有什么区别 [英] What are the difference between generic Type(T) vs any in typescript
问题描述
function identity(arg: any): any {
return arg;
}
功能2
Function 2
function identity<T>(arg: T): T {
return arg;
}
功能3
Function 3
function identity<T>(arg: T[]): T[] {
return arg;
}
功能1&如果我们传递任何类型的
数据类型
,则接受3,但如果我们传递数组
,则函数2不接受。 泛型类型在编译时接受所有类型的数据类型。但这里为什么不接受?
Function 1 & 3 is accepted if we passing any kind of
data type
, But the function 2 does not accept if we pass anarray
. generic type is accepting all kind of data type on compile time. but here why it does not accept?
哪个功能有利于提高性能(功能1或功能3)?
Also which function is good for better performance ( function 1 or function 3)?
推荐答案
如果这是一个只返回一个参数且没有类型限制的身份函数,则没有区别:
There is no difference if this is identity function that just returns an argument and used without type restrictions:
const foo: any = fn(['whatever']);
类型代码有所不同:
const foo: string = fn('ok');
const bar: string = fn([{ not: 'ok' }]);
此外,泛型类型的使用提供了语义。此签名表明该函数是无类型的并返回任何内容:
Also, the usage of generic type provides semantics. This signature suggests that the function is untyped and returns anything:
function fn(arg: any): any { ... }
此签名表明该函数返回与其参数相同的类型:
This signature suggests that the function returns the same type as its argument:
function fn<T>(arg: T): T { ... }
实际函数通常比 return arg
示例更有意义。通用类型可以受益于类型限制(而任何
显然不能):
Real functions are usually more meaningful than just return arg
example. Generic type can benefit from type restrictions (while any
obviously can't):
function fn<T>(arg: T[]): T[] {
return arg.map((v, i) => arg[i - 1]);
}
但是当函数与其他泛型一起使用时,好处会变得更加明显类和泛型函数(如果涉及非泛型函数则被删除):
But the benefits become more obvious when the function is used in conjunction with other generic classes and generic functions (and eliminated if non-generics are involved):
function fn<T>(arg: T[]): T[] {
return Array.from(new Set<T>(arg));
}
这样可以始终如一地维持 T
输入(参数)和输出(返回值)之间的类型:
This allows to consistently maintain T
type between input (argument) and output (returned value):
const foo: string[] = fn(['ok']);
const bar: string[] = fn([{ not: 'ok' }]);
性能不会有任何差异,因为TypeScript类型仅在设计时存在。
There cannot be any difference in performance because TypeScript types exist only on design time.
这篇关于泛型类型(T)与打字稿中的任何类型有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!