1

I know that we can extract type possibilies using an array:

const fruits = ['Apple', 'Pear', 'Banana'] as const
type fruitType = typeof fruits[number] // "Apple" | "Pear" | "Banana"

I wonder if we can do this using object indexes instead?

const fruits = {
  apple: { shape: 'round', color: 'red' },
  pear: { shape: 'pear-like', color: 'yellow' },
  banana: { shape: 'banana-shaped', color: 'banana-colored' }
}
type fruitType = typeof indexes of fruits // "apple" | "pear" | "banana"

Thanks!

3
  • Those are generally termed "keys", not "indexes", when applied to objects. Thus the keyword in TypeScript keyof... Commented Oct 19, 2021 at 19:33
  • It looks very strange. Usually the union type is used fro those puposes - type fruitTypes = 'Apple' | 'Pear' | 'Banana'. Then that type is implemented for both const fruits: fruitTypes and const fruits: { [key: fruitTypes]: unknown }; Commented Oct 19, 2021 at 19:40
  • you mean this ? type keys = keyof typeof fruits; Commented Oct 19, 2021 at 19:48

1 Answer 1

2

I believe this is what you are looking for:

type fruitType = keyof typeof fruits // "apple" | "pear" | "banana";

Here is a link to the documentation as @jcalz suggested, and the Playground

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

1 Comment

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.