我有對話資料,其中一些鍵名包含其他鍵的值。是否可以在不使用的情況下為此顯式創建型別[key: string]?
資料看起來像這樣,在接下來的兩個“新”鍵中使用兩個 uid:
{
uid0: "212122323",
uid1: "797789667",
new212122323: true,
new797789667: false
}
我希望得到這樣的型別(偽型別):
export type Conversation = {
uid0: string,
uid1: string,
["new" this.uid0]: boolean,
["new" this.uid1]: boolean,
}
uj5u.com熱心網友回復:
如果資料來自任何外部來源,這是不可能的。像這樣的型別只能靜態作業,這意味著在編譯時。如果您在應用程式編譯時不知道用戶 id,那么您就無法創建在這些 id 上提供強型別的型別。
所以我認為你最接近的是:
type Conversation = {
[key: `uid${number}`]: string
[key: `new${number}`]: boolean
}
像這樣作業:
const data: Conversation = {
uid0: "212122323",
uid1: "797789667",
new212122323: true,
new797789667: false
}
const testA = data.uid123 // string
const testB = data.new456 // boolean
并且應該檢測帶有錯誤的無效道具:
const badData: Conversation = {
uid0: "212122323",
someProps: 'I dont belong here', // error
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436136.html
