我有每個欄位都是字串陣列的物件。我也有字串變數,它只能具有基于物件中的陣列值的值。
現在我想檢查這個字串屬于哪個陣列(哪個物件欄位)。我只是通過簡單地使用來做到這一點,includes()并且代碼作業正常,但出于某種原因,TS 抱怨。即使某個陣列可以具有某些值,但我卻“從不”除外。我簡化了代碼以僅顯示 TS 問題。
const demo = {
a: ['value1', 'value2'],
b: ['value3'],
} as const
let demoValue: typeof demo[keyof typeof demo][number] // possible "value1" "value2" "value3"
demoValue = 'value3' // some user interaction
const test = (parent: keyof typeof demo, value: typeof demoValue) => {
console.log(demo[parent].includes(value)) // "type 'string' is not assignable to type 'never'"
}
test('a', 'value2') // ok
test('WRONG', 'value2') // there is TS error, so ok
test('a', 'WRONG') // there is TS error, so ok
操場
我可以通過制作來“修復”它,includes(value as never)但我覺得這不是真正的修復,而是針對錯誤型別的更多解決方法......
uj5u.com熱心網友回復:
您可以使用型別斷言,但在這種情況下,有一個更安全的選擇。如果您宣告 awideList是所有可能值的并集的陣列,則可以將串列的并集分配給它,而無需使用as.
const test = (parent: keyof typeof demo, value: typeof demoValue) => {
const wideList: readonly (typeof demoValue)[] = demo[parent];
console.log(wideList.includes(value));
}
游樂場鏈接
更新:剛剛想到另一個解決方案,您可以定義一個函式includes(而不是 OO),它能夠更好地處理串列的聯合:
const includes = <T>(arr: readonly T[], x: T): boolean => arr.includes(x)
const test = (parent: keyof typeof demo, value: typeof demoValue) => {
console.log(includes(demo[parent], value))
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450788.html
標籤:打字稿
