考慮這段代碼:
type T<A> = {
[A]: true
}
鑒于這種型別,我想像這樣使用它:
type Obj = T<"key">
要生成與此型別等效的型別:
type Obj = {
key: true
}
但是,編譯器給了我這個錯誤:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
我能以某種方式證明,A型別變數只能由字串文字嗎?就像是:
type T<A extends ?literal?> = {
[A]: true
}
uj5u.com熱心網友回復:
像這樣的東西。A extends keyof any不完全是字面量型別,所以我們需要在這里使用映射型別。
type T<A extends keyof any> = {
[K in A]: true;
};
// It's equivalent to built-in Record type, so you should probably use it
// type T<K extends keyof any> = Record<K, true>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409673.html
標籤:
