HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

How to get a variable type in Typescript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripthowvariabletypeget

Problem

I have a variable.

abc:number|string;


How can I check its type? I want to do something like below:

if (abc.type === "number") {
    // do something
}

Solution

For :

abc:number|string;


Use the JavaScript operator typeof:

if (typeof abc === "number") {
    // do something
}


TypeScript understands typeof 🌹

This is called a typeguard.
More

For classes you would use instanceof e.g.

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}


There are also other type guards e.g. in etc https://basarat.gitbook.io/typescript/type-system/typeguard

Code Snippets

abc:number|string;
if (typeof abc === "number") {
    // do something
}
class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}

Context

Stack Overflow Q#35546421, score: 467

Revisions (0)

No revisions yet.