typescript - 为什么我们需要在打字稿中编写函数的泛型?例如函数填充(){}
问题描述
我是打字稿的新手,所以我对此有疑问。其中之一是:
function fill**<IDontKnow>**(array: any[], value: IDontKnow): IDontKnow[] {
return array.map(() => value);
}
我理解所有书面泛型的目的,但星号中的那个。这是什么意思/做什么?
解决方案
泛型通常用于两个目的:
- 告诉编译器从引用中推断/替换类型。
- 告诉编译器将类型强制到目标上。
根据您的代码段(或在操场上查看)检查此示例:
function fill<T>(array: any[], value: T): T[] {
return array.map(() => value);
}
/* Purpose 1: To tell the compiler to infer/substitute a type from a reference. */
// T is automatically inferred as `string` type, and in turn the type of `infer0` is automatically inferred as `string[]`.
const infer0 = fill([null, null, null], 'hello');
// T is automatically inferred as `number` type, and in turn the type of `infer1` is automatically inferred as `number[]`.
const infer1 = fill([null, null, null], 1);
// T is automatically inferred as `boolean` type, and in turn the type of `infer2` is automatically inferred as `boolean[]`.
const infer2 = fill([null, null, null], false);
/* Purpose 2: To tell the compiler to force a type onto a target. */
// T is forced to be `string`, so now the `value` argument have to be a value of type `string`.
const force0 = fill<string>([null, null, null], 1); // should error
// T is forced to be `number`, so now the `value` argument have to be a value of type `number`.
const force1 = fill<number>([null, null, null], false); // should error
// T is forced to be `boolean`, so now the `value` argument have to be a value of type `boolean`.
const force2 = fill<boolean>([null, null, null], 'hello'); // should error
这fill**<T>**
只是用 name 声明泛型的语法T
,其中T
可以是任何名称。
它与变量声明的概念相同。当您这样做时const T = 'hello'
,您就是在声明一个常量变量并为其命名T
。
推荐阅读
- javascript - localStorage 和带有页面 id 的 url
- authentication - 如何为 Entity Framework 和 ASP.Net Core Identity 使用预先存在的表
- java - 抽象类避免创建多个对象实例来传递不同的输入
- c++ - C++ 动态数组每次添加都会将大小增加 1 - 错误
- ios - 使用虚拟摇杆下降会在 Mavic 2 pro 上产生漂移问题
- r - 错误:列 `` 的类型为 NULL 不受支持
- java - JMeter 在 CLI 中给出错误百分比,但在 GUI 中没有
- java - 如何解决:用户“net”登录失败?
- java - 从三叶草代码覆盖中排除模块
- jquery - 选择 2 jQuery 在 laravel 6 中不起作用