Chris Drackett
Chris Drackett

Reputation: 1327

how to get the type from a object value based on a variable

I have the following type:

type Core = {
  a: string
  b: number
}

I would like to be able to get the type of one of the entities for use elsewhere.

pseudocode:

const c: <the type of Core.a> = 'hello'

basically I want a type that takes a variable (a in this case) that then returns the value from the above object.

Upvotes: 2

Views: 399

Answers (1)

jcalz
jcalz

Reputation: 330286

Looks like you want indexed access types, aka lookup types. If T is a type, and K is the type of one of its keys (or a union of such types), then T[K] is the type of the property of that key (or a union of such properties). In your case, T is Core and K is the string literal type "a":

const c: Core["a"] = 'hello'; // okay

Note that lookup types only support bracket notation, T["a"]; you can't use dot notation like T.a, even when the key is a string literal. (Dot notation would cause a potential name collision with namespaces/modules; if you had a namespace named T that exports a type named a then T.a is the name of that type.)

Playground link to code

Upvotes: 1

Related Questions