Is there a way in TypeScript to declare that a variable is a keyof
some Record
without prior knowledge of the keys?
For instance, consider an API response returning JSON data. Is it possible to define a type for the keys of this payload to ensure that when indexing through the payload, the value will not be undefined? Or must we manually check for undefined each time we access a property in the payload object?
Here's an example:
const payload: Record<string, ValidValue> = await myApiCall()
const prop1 = 'a'
const prop2 = 'b'
if (isValidKey(prop1, payload)) {
const value1 = payload[prop1] // here, `value1` should have type `ValidValue`
}
const value2 = payload[prop2] // here, `value2` should have type `ValidValue | undefined`