0

Is there some way to extract property values from array?

const d = [{id: 'Cat'}, {id: 'Dog'}]

type ids = ??? //insert code here, type should be 'Cat' | 'Dog'

(It would also work if it generates a const enum)

1 Answer 1

4

When you declare d with as const, you can extract the information like this:

const d = [{id: 'Cat'}, {id: 'Dog'}] as const

type IDs = typeof d[number]["id"]

Playground

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

4 Comments

To add an explanation why as const is needed: literal types won't work otherwise, so you'd only be able to get the less strict string. typescriptlang.org/docs/handbook/2/…
is it possible to do as const when importing a json file?
I would say no. It would not work with an imported json file. This only works with object literals in your typescript code.
Here is an open issue github.com/microsoft/TypeScript/issues/32063 for allowing to import json with as const. So this may be possible in the future.

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.