I can do this
const keys = {
"hi": {name: "ho"}
}
type U = [keyof typeof keys][0]; // "hi"
Can I do it also with array values?
const data = [
{ name: "hi" }
];
type T = typeof data[0]["name"]; // string not "hi"
I can do this
const keys = {
"hi": {name: "ho"}
}
type U = [keyof typeof keys][0]; // "hi"
Can I do it also with array values?
const data = [
{ name: "hi" }
];
type T = typeof data[0]["name"]; // string not "hi"
Because the elements of an array can change at runtime, TS will just infer the type for data as Array<{ name: string }>. You have to explicitly set the type of the data array as readonly, so TS can infer the type for the first element inside the data array as {name: "hi"}.
The solution is to just add as const to the data array.
const data = [
{name: "hi"}
] as const;
// this will make TS infer the type for data as readonly[{ readonly name: "hi";}]
See the demo in ts playground