我正在嘗試學習打字稿泛型,但無法理解這兩種型別之間的區別:
type A<T> = (x: T) => T;
type B = <T>(x: T) => T;
我只在 yt 上找到了一個視頻,但不幸的是這不足以讓我的大腦理解......
any1有簡單的解釋嗎?謝謝!
uj5u.com熱心網友回復:
與type A<T> = (x: T) => T;一般的具有使用型別時,要傳遞,例如:
// here a is (c: string) => string;
let a: A<string> = x => x;
// a only accept string
a('foo')
在type B = <T>(x: T) => T;呼叫函式時傳遞泛型:
// no generic yet
let b: B = x => x;
// here b is (x: number) => number;
b<number>(42);
// here b is (x: boolean) => boolean;
b<boolean>(true);
// you can omit the generic since TS will infer it
// here b is (x: string) => string;
b('hello')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315197.html
下一篇:從JSON檔案推斷字串文字型別
