gpt4 book ai didi

typescript - TypeScript 中的泛型类型参数 T 是什么?

转载 作者:行者123 更新时间:2023-12-05 09:29:43 30 4
gpt4 key购买 nike

浏览 TS 手册。 https://www.typescriptlang.org/docs/handbook/2/functions.html

In TypeScript, generics are used when we want to describe acorrespondence between two values. We do this by declaring a typeparameter in the function signature:

function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}

By adding a type parameter Type to this function and using it in twoplaces, we’ve created a link between the input of the function (thearray) and the output (the return value). Now when we call it, a morespecific type comes out:

在这种情况下,Type 是关键字吗?当我只看到 T 时,这是同一回事吗?

我对这部分的理解正确吗?通过添加我们告诉 Typescript 将输入的任何类型分配给输出?

最佳答案

In this case is Type a keyword?

在您的示例中,Typegeneric type parameter (type variable) .

When I see just T is that the same thing?

假设 token 在同一位置,是的。

By adding we are telling Typescript to assign whatever type the input is to the output?

将它们类比于函数中的参数,但对于类型而言,这对我很有帮助。你实际上是在告诉 typescript :

“我正在创建一个名为 Type 的类型参数(变量)。我将在该函数中接受一个参数,该参数将是一个数组,您应该使用每个元素的类型在数组中作为实际类型代替 Type。我将返回数组元素之一,因此此函数的返回类型应与数组元素之一的类型相同(或者 undefined 如果我使用一个没有值的索引)。”

Now, there's one more potentially confusing part to this, based on the example that you provided, which is "Why doesn't TypeScript account for the possibility of undefined when indexing an array element using square brackets?", and that's covered in this answer.

这是一个具体的例子:

TS Playground

function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}

// This type is: number[]
const arr1 = [1, 2, 3];

// When giving `arr1` as the argument to `firstElement`,
// `Type` will become `number` because each element in `arr1`
// is `number`. So the result will be: number | undefined
const result1 = firstElement(arr1);

// This type is: string[]
const arr2 = ['hello', 'world'];

// When giving `arr2` as the argument to `firstElement`,
// `Type` will become `string` because each element in `arr2`
// is `string`. So the result will be: string | undefined
const result2 = firstElement(arr2);

这是另一个使用 T 而不是 Type 作为泛型类型参数的例子:

TS Playground

function elementAtIndex<T>(arr: T[], index: number): T | undefined {
return arr[index];
}

const arr = ['zero', 'one', 'two'];

const zero = elementAtIndex(arr, 0); // string | undefined
console.log(zero); // "zero"

const three = elementAtIndex(arr, 3); // string | undefined
console.log(three) // undefined

FWIW, elementAtIndex in the example above is just a functional version of Array.prototype.at(), which should be in an upcoming release of TypeScript (probably v4.6).

关于typescript - TypeScript 中的泛型类型参数 T 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70453731/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com