使用 Object.entries() 時,它回傳正確的值型別,但鍵string[]是不正確的。我想強制 TS 知道我的密鑰。我試圖as const在物件上使用,但這什么也沒做。
在這種情況下是否可以斷言型別?
const demo = {
a: 'TEST',
b: 222,
} as const
Object.entries(demo)
.forEach(([key, value]) => { // key is string and not "a" | "b"
console.log([key, value])
})
// reproduce same types as above
Object.entries(demo)
.forEach(([key, value]: [string, typeof demo[keyof typeof demo]]) => {
console.log([key, value])
})
// now trying to change string to actual keys, error :(
Object.entries(demo)
.forEach(([key, value]: [keyof typeof demo, typeof demo[keyof typeof demo]]) => {
console.log([key, value])
})
// so instead trying to force somehow type assertion
Object.entries(demo)
.forEach(([key as keyof typeof demo, value]) => { // how to make assertion???
console.log([key, value])
})
操場
uj5u.com熱心網友回復:
鍵為 string[] 不正確
它被設計成那樣,因為物件可以擴展。你可能知道它沒有被擴展,但是型別系統不能強制它。一個例子:
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
department: string;
}
const someFunction (person: Person) {
Object.entries([key, value] => {
// `key` will sometimes be 'name' or 'age', but those aren't its only
// values. In this example, it will be 'department', and it could be
// absolutely any string, hence the type string.
});
}
const alice: Person = { name: 'alice', age: 30 }
const bob: Employee = { name: 'bob', age: 30, department: 'legal' }
someFunction(alice); // legal of course
someFunction(bob); // Also legal
如果您想斷言您知道沒有額外的屬性,以下可能是最簡單的方法:
Object.entries(demo)
.forEach(([k, value]) => {
const key = k as keyof typeof demo
console.log([key, value])
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/454823.html
標籤:打字稿
上一篇:包裝函式時保留泛型
下一篇:如何在映射值中反向參考映射鍵?
