snippettypescriptCritical
How to get a variable type in Typescript?
Viewed 0 times
typescripthowvariabletypeget
Problem
I have a variable.
How can I check its type? I want to do something like below:
abc:number|string;How can I check its type? I want to do something like below:
if (abc.type === "number") {
// do something
}Solution
For :
Use the JavaScript operator
TypeScript understands
This is called a typeguard.
More
For classes you would use
There are also other type guards e.g.
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/typeguardCode 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.