function identity<String>(arg: String): String {
return arg;
}
let myIdentity = identity([2]);
console.log()
嗨,有人可以幫助我理解為什么即使我傳遞了一組數字也不會引發任何型別錯誤嗎?
- 是不是因為型別是 "String" 而不是 "string" ,它查找物件而不是原始物件?
- 如果答案是“是”,如果我將所有內容都更改為字串,我會收到錯誤訊息,說從未使用過字串
function identity<string>(arg: string): string {
return arg;
}
let myIdentity = identity([2]);
console.log(myIdentity )
'string' is declared but its value is never read.
uj5u.com熱心網友回復:
您正在隱藏內置型別String并string使用它們的名稱作為通用引數。只需使用一個不是內置的引數名稱來解決它:
TS 游樂場鏈接
function identity<T extends string>(value: T): T {
return value;
}
identity([2]); // error [2] doesn't extend string
identity('2'); // ok
如果你想要一個沒有任何約束的通用標識函式,你可以使用一個不受約束的型別引數:
TS 游樂場鏈接
function identity<T>(value: T): T {
return value;
}
const numberArrayValue = identity([2]); // number[]
const objectValue = identity({b: 2}); // { b: number; }
const stringLiteralValue = identity('2'); // "2"
const numberLiteralValue = identity(2); // 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375626.html
標籤:javascript 打字稿 打字稿打字
下一篇:如何動態渲染圖示?
