6

Is there a way to define a type by the values of a field in an array?

To simplify my question... Given that I have a static array:

const arr = [
  {name: 'cat', language: 'meow'},
  {name: 'dog', language: 'bark'},
  {name: 'cow', language: 'moo'}
]

And I want to be able to create a function that gets the language based on the name field defined like so

function getLanguage(name: X) {

What can I define the type X to be so that I can limit X (the parameter of that function) to be any of the name fields in that list of objects?

1

1 Answer 1

9
const arr = [
  {name: 'cat', language: 'meow'},
  {name: 'dog', language: 'bark'},
  {name: 'cow', language: 'moo'}
] as const // pay attention here

type Name = (typeof arr)[number]['name']; // evaluates into 'cat' | 'dog' | 'cow'

function getLanguage(name: Name) { }

Few things to understand:

  • as const in order to say to TS that type should be narrowed to exact values
  • (typeof arr)[number] - it gives as array element type, as number is a key of array mapped type
  • (typeof arr)[number]['name'] - it gives type of name field of array element type

If you don't need to narrow the type and string satisfy you for the name field then simply not append as const, in result (typeof arr)[number]['name'] will be evaluated to string type.

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

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.