首页 > 解决方案 > 为什么我们需要在打字稿中编写函数的泛型?例如函数填充(){}

问题描述

我是打字稿的新手,所以我对此有疑问。其中之一是:

function fill**<IDontKnow>**(array: any[], value: IDontKnow): IDontKnow[] {
  return array.map(() => value);
}

我理解所有书面泛型的目的,但星号中的那个。这是什么意思/做什么?

标签: typescript

解决方案


泛型通常用于两个目的:

  1. 告诉编译器从引用中推断/替换类型。
  2. 告诉编译器将类型强制到目标上。

根据您的代码段(或在操场上查看)检查此示例:

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


推荐阅读