#Why isn't the key inferred correctly?

4 messages · Page 1 of 1 (latest)

royal pulsarBOT
#
jupecito#0

Preview:```ts
export default function Table<
V extends Object,
K extends {
[key in keyof V]: {
label: string
title?: (label: string) => any
content?: (value: V) => any
}
}

({rows, columns}: {rows: V[]; columns: K}) {
rows.map(row => {
Object.entries(row).map(([key, value]) => {
// why isn't the key inferred correctly?
console.log(columns[key].label)
// like:
console.log(columns[key as keyof V].label)
})
})
}```

lucid trench
#

!:unsafe-keys

royal pulsarBOT
#
retsam19#0
`!retsam19:unsafe-keys`:

Since TS allows objects to have extra properties not specified in the type, it doesn't assume that all the keys on the type are the only keys on the object. This means that Object.keys returns string[] not a specific type, and for(const key in obj), key is string, (not keyof typeof obj).

If you wish to assume otherwise, this utility is often helpful:

// A signature for `Object.keys` that assumes the only keys are the ones indicated by the type
const unsafeKeys = Object.keys as <T>(obj: T) => Array<keyof T>;
alpine crest
#

I ended up solving it like this: