正在閱讀 TS 手冊。 https://www.typescriptlang.org/docs/handbook/2/functions.html
在 TypeScript 中,當我們想要描述兩個值之間的對應關系時,會使用泛型。我們通過在函式簽名中宣告一個型別引數來做到這一點:
function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}
通過向這個函式添加一個型別引數 Type 并在兩個地方使用它,我們在函式的輸入(陣列)和輸出(回傳值)之間創建了一個鏈接。現在當我們呼叫它時,會出現一個更具體的型別:
在這種情況下是Type關鍵字?當我看到只是T那是同一件事嗎?
我是否正確理解了這一部分?通過添加我們告訴 Typescript 將輸入的任何型別分配給輸出?
uj5u.com熱心網友回復:
在這種情況下是
Type關鍵字?
在您的示例中,Type是泛型型別引數(型別變數)。
當我看到只是
T那是同一件事嗎?
假設令牌在相同的位置,是的。
通過添加我們告訴 Typescript 將輸入的任何型別分配給輸出?
將它們類似于函式中的引數對我來說很有幫助,但對于型別。你有效地告訴打字稿:
“我正在創建一個名為 的型別引數(變數)Type。我將在此函式中接受一個引數,該引數將是一個陣列,您應該使用陣列中每個元素的型別作為實際型別來代替Type。我將回傳陣列元素之一,因此該函式的回傳型別應該與陣列元素之一的型別相同(或者undefined如果我使用沒有值的索引)。”
現在,根據您提供的示例,還有一個可能令人困惑的部分,即“為什么在使用方括號對陣列元素進行索引時,TypeScript 不考慮 undefined 的可能性?”,并且在此答案中進行了介紹.
這是一個具體的例子:
TS游樂場
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游樂場
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在上面的示例中只是 的功能版本Array.prototype.at(),它應該在即將發布的 TypeScript 版本中(可能是v4.6)。
uj5u.com熱心網友回復:
不,這里Type是一個簡單的識別符號,它標識一個型別引數。通常型別引數以大寫字母命名,例如T,但更具描述性的名稱會很有用。
這個宣告說:
function firstElement // We are defining a function
<Type> // The function has a type parameter
(arr: Type[]): // and regular parameters of that type.
Type | undefined // It returns either a value of the type
// given by the type parameter, or undefined.
這個想法是你可以傳遞一個特定型別的元素陣列,并期望一個相同型別的元素,靜態檢查:
firsElement<number>([1,2,3])將回傳 a number,編譯器將保證它不是字串或物件。
firstElement<number>(['a', 'b'])甚至不會編譯,因為它要求一個數字陣列 (by <number>),但接收一個字串陣列。
firstElement<number>([])將回傳undefined,因為沒有要回傳的第一個元素。這是| undefined回傳型別中的子句所允許的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390791.html
