Categories
TypeScript Answers

How to get the type of a property of a TypeScript class using keyof operator?

Spread the love

Sometimes, we want to get the type of a property of a TypeScript class using keyof operator.

In this article, we’ll look at how to get the type of a property of a TypeScript class using keyof operator.

How to get the type of a property of a TypeScript class using keyof operator?

To get the type of a property of a TypeScript class using keyof operator, we can use lookup types.

For instance, we write

type BarType = FooType["bar"];

to get the type of the bar property of an object of FooType with FooType["bar"].

And then we assign the returned type to BarType.

Conclusion

To get the type of a property of a TypeScript class using keyof operator, we can use lookup types.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *