DEV Community

Cover image for How to get the type of another variable in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the type of another variable in TypeScript?

Originally posted here!

To get the type of another variable, you can use the typeof type operator in TypeScript.

TL;DR

// a simple variable
let firstName = "John Doe";

// get the type of variable `firstName`
type SimpleType = typeof firstName; // string
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a variable called firstName with a value of John Doe like this,

// a simple variable
let firstName = "John Doe";
Enter fullscreen mode Exit fullscreen mode

Now to get the type of the variable firstName dynamically or programmatically, we can use the typeof type operator like this,

// a simple variable
let firstName = "John Doe";

// get the type of variable `firstName`
type SimpleType = typeof firstName; // string
Enter fullscreen mode Exit fullscreen mode

Now if you hover over the SimpleType type, you can see that it is of string type which is what we want to happen.

We have successfully got the type of another variable in TypeScript. Yay! 🥳.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)