Huakun Shen
Huakun Shen

Reputation: 404

TypeScript: Get type of a property

I am trying to get the type of a property in another type.

For example, I have a type A, and I need to get the type of b.

The only method I could come up with is make a instance of A and get b's type.

type A = {
  a: string
  b: number
}
const a: A = null


type B = typeof a.b

Upvotes: 3

Views: 7372

Answers (2)

rjferguson
rjferguson

Reputation: 623

Use the indexed access type. Adapting the typescript example to your example above:

type A = {
  a: string
  b: number
}
type B = A["b"];

It is no longer necessary to create an instance, which makes this preferable. From the docs at https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html.

Upvotes: 1

You can use typeof

type A = {
    a: string
    b: number
}
const a: A = null

type B = typeof a.b

https://www.typescriptlang.org/docs/handbook/2/typeof-types.html

Upvotes: 2

Related Questions