How to get the type of another variable in TypeScript?

January 20, 2022 - 1 min read

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

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";

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

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 😃.