0

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"

https://www.typescriptlang.org/play/?ssl=9&ssc=1&pln=10&pc=1#code/MYewdgzgLgBAJgQygmBeGBtAUDXMDeMYCAtgKYBcMARABYCW1MAvlgLoDcWWoksA1mQCeENARx46jKvmLkqdENVassUIQAcyMACpj1WkADN4SBBgAMbDNTllqnNZu0BVMRkFDjMA2W+eIaysOIA

2 Answers 2

1

Just add as const to your data:

const data = [
    { name: "hi" }
] as const;

Without as const, data is inferred as Array<{name: string}>. You do not need as const for keys as it is inferred {hi: {name: string}}

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.