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

Answer from basarat on Stack Overflow
๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ 2 โ€บ typeof-types.html
TypeScript: Documentation - Typeof Type Operator
TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property:
๐ŸŒ
Convex
convex.dev โ€บ advanced โ€บ type operators & manipulation โ€บ typeof
Using TypeScript typeof for advance type safety
The TypeScript typeof operator solves exactly this problem. It lets you capture types from existing values at compile time, creating a single source of truth between your runtime data and type definitions.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Operators โ€บ typeof
typeof - JavaScript - MDN Web Docs - Mozilla
// Numbers typeof 37 === "number"; typeof 3.14 === "number"; typeof 42 === "number"; typeof Math.LN2 === "number"; typeof Infinity === "number"; typeof NaN === "number"; // Despite being "Not-A-Number" typeof Number("1") === "number"; // Number tries to parse things into numbers typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number typeof 42n === "bigint"; // Strings typeof "" === "string"; typeof "bla" === "string"; typeof `template literal` === "string"; typeof "1" === "string"; // note that a number within a string is still typeof string typeof type
๐ŸŒ
Omarileon
omarileon.me โ€บ blog โ€บ typescript-typeof
mari. | A Comprehensive Guide to the typeOf Operator in Typescript
March 5, 2024 - In JavaScript (and TypeScript), "typeof" is a type-checking operator. It returns a string indicating the type of whatever operand you pass to it.
๐ŸŒ
Graphite
graphite.com โ€บ guides โ€บ typescript-typeof-operator
TypeScript typeof operator - Graphite
In TypeScript, typeof is a powerful operator that can be used to grab the type of a variable, allowing developers to work with type information dynamically.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ typescript โ€บ typeof-type-operator
TypeScript Typeof Type Operator: Syntax, Use Cases, and Examples
The typeof operator in TypeScript lets you extract the type of a variable or value and reuse it throughout your code.
Find elsewhere
Top answer
1 of 3
423

Short answer:

You can't use typeof at runtime to check for interface types, which only exist at compile time. Instead you can write a user-defined type guard function to check for such types:

const fruit = ["apple", "banana", "grape"] as const;
type Fruit = (typeof fruit)[number];
const isFruit = (x: any): x is Fruit => fruit.includes(x);

let myfruit = "pear";
if (isFruit(myfruit)) {
  console.log("My fruit is of type 'Fruit'");
}

Long answer follows:


You might be confused about the difference between values and types in TypeScript, especially as it relates to the typeof operator. As you may be aware, TypeScript adds a static type system to JavaScript, and that type system gets erased when the code is transpiled. The syntax of TypeScript is such that some expressions and statements refer to values that exist at runtime, while other expressions and statements refer to types that exist only at design/compile time. Values have types, but they are not types themselves. Importantly, there are some places in the code where the compiler will expect a value and interpret the expression it finds as a value if possible, and other places where the compiler will expect a type and interpret the expression it finds as a type if possible.

The typeof operator leads a double life. The expression typeof x always expects x to be a value, but typeof x itself could be a value or type depending on the context:

let bar = {a: 0};
let TypeofBar = typeof bar; // the value "object"
type TypeofBar = typeof bar; // the type {a: number}

The line let TypeofBar = typeof bar; will make it through to the JavaScript, and it will use the JavaScript typeof operator at runtime and produce a string. But type TypeofBar = typeof bar; is erased, and it is using the TypeScript type query operator to examine the static type that TypeScript has assigned to the value named bar.

In your code,

let myfruit = "pear";
if (typeof myfruit === "Fruit") { // "string" === "Fruit" ?!
    console.log("My fruit is of type 'Fruit'");
}

typeof myfruit is a value, not a type. So it's the JavaScript typeof operator, not the TypeScript type query operator. It will always return the value "string"; it will never be Fruit or "Fruit". You can't get the results of the TypeScript type query operator at runtime, because the type system is erased at runtime. You need to give up on the typeof operator.


What you can do is check the value of myfruit against the three known Fruit string literals... like, for example, this:

let myfruit = "pear";
if (myfruit === "apple" || myfruit === "banana" || myfruit === "grape") {
  console.log("My fruit is of type 'Fruit'");
}

Perfect, right? Okay, maybe that seems like a lot of redundant code. Here's a less redundant way to do it. First of all, define your Fruit type in terms of an existing array of literal values... TypeScript can infer types from values, but you can't generate values from types.

const fruit = ["apple", "banana", "grape"] as const;
export type Fruit = (typeof fruit)[number];

You can verify that Fruit is the same type as you defined yourself manually. Then, for the type test, you can use a user-defined type guard like this:

const isFruit = (x: any): x is Fruit => fruit.includes(x);

isFruit() is a function which checks if its argument is found in the fruit array, and if so, narrows the type of its argument to Fruit. Let's see it work:

let myfruit = "pear";
if (isFruit(myfruit)) {
  console.log("My fruit is of type 'Fruit'");
}

That type guard also lets the compiler know that inside the "then" clause of the if statement, that myfruit is a Fruit. Imagine if you had a function that only accepts Fruit, and a value that may or may not be a Fruit:

declare function acceptFruit(f: Fruit): void;
const myfruit = Math.random() < 0.5 ? "pear" : "banana";

You can't call the function directly:

acceptFruit(myfruit); // error, myfruit might be "pear"

But you can call it inside the "then" clause after checking it:

if (isFruit(myfruit)) {
  acceptFruit(myfruit); // okay, myfruit is known to be "banana"
}

Which is presumably why you want to check against your custom type in the first place. So that lets you do it.


To recap: you can't use typeof. You can compare against strings. You can do some type inference and a type guard to eliminate duplicated code and get control flow type analysis from the compiler.

Playground link to code

2 of 3
11

typeof in TS:

The typeof operator in TS can be used in 2 different contexts:

  1. In an expression/value context to return a string of its type. This is just the JavaScript typeof operator and will remain after a compile.
  2. In a type context to make the type similar to an existing expression/value. This is a TS construct to help us express ourselves more easily with certain types. This will be compiled away and not be present in the compiled JavaScript

Examples:

Expression/value context

const hi = 'hi';
const one = 1;
const obj = {};

console.log(typeof hi, typeof 1, typeof obj);
// [LOG]: "string",  "number",  "object"

Type context:

const obj1 = {foo: 1, bar: true};
const obj2 = {foo: 1, bar: ''};

// test has the type according to the structure of obj1
const test: typeof obj1 = {foo: 1, bar: true};
// typeof obj1 is the same as:
type sameAsTypeofObj1 = {foo: number, bar: string}


// test2 has the type according to the structure of obj1
const test2: typeof obj2 = {foo: 1, bar: true};
// In test2 we get a compile error since bar is not correct
// Since the type of obj2 is {foo: number, bar: string} we get the error:
// Type 'boolean' is not assignable to type 'string'

For your specific problem I think you should use user defined type guards. Here is an example:

type Fruit = "apple" | "banana" | "grape";

let myfruit = "apple";

// user defined type guard
function isFruit(fruit: string): fruit is Fruit {
  return ["apple", "banana", "grape"].indexOf(fruit) !== -1;
}

if (isFruit(myfruit)) {
    // if this condition passes 
    // then TS compiler knows that myfruit is of the Fruit type
    console.log(`${myfruit} is a Fruit.`}
}
๐ŸŒ
Fjolt
fjolt.com โ€บ article โ€บ typescript-typeof-operator
How the typeof Operator works in TypeScript
The most basic application of typeof in TypeScript is the creation of new basic types. If we are defining our own custom types in TypeScript, we can use typeof to copy the type of an existing item.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ typescript โ€บ typescript typeof
TypeScript TypeOf - Scaler Topics
May 4, 2023 - The typeof type guards can be acknowledged in two different forms: typeof t === "typename" and typeof t !== "typename" where typename is one of the return values of typeof. The return values can be undefined, number, string, boolean, object or function. The syntax for defining the TypeScript typeof keyword is as follows:
๐ŸŒ
Tektutorialshub
tektutorialshub.com โ€บ home โ€บ typescript โ€บ typeof in typescript
TypeOf in TypeScript - Tektutorialshub
March 15, 2023 - The TypeScript infers the type from the initialization as { code: string, name: string }. We can create another variable employee with the same type as person by using the TypeOf query (typeof person).
๐ŸŒ
Maya Shavin
mayashavin.com โ€บ articles โ€บ types-from-constants-typescript
Using keyof and typeof for types efficiently in TypeScript
February 15, 2023 - Additionally, we can use typeof in TypeScript to act as the type guard within a conditional block, just like in JavaScript, though in this case, it will mainly work for primitive types like string, object, function, etc...
๐ŸŒ
Learn TypeScript
learntypescript.dev โ€บ 07 โ€บ l3-typeof-type-guard
Using a `typeof` type guard | Learn TypeScript
typeof is a JavaScript operator that returns a string indicating the JavaScript type of the operand. ... So, TypeScript has cleverly narrowed the type of item in the branches of logic following the typeof check.
๐ŸŒ
Execute Program
executeprogram.com โ€บ courses โ€บ advanced-typescript โ€บ lessons โ€บ typeof
Advanced TypeScript: Typeof
Learn programming languages like TypeScript, Python, JavaScript, SQL, and regular expressions. Interactive with real code examples.
๐ŸŒ
Turing
turing.com โ€บ kb โ€บ check-type-of-objects-variables-in-typescript
How to Check Type of Objects & Variables in Typescript
The typeof operator is a standard JavaScript operator recognized by TypeScript for checking the type of variables and objects.
๐ŸŒ
typescriptlang.org
typescriptlang.org โ€บ docs โ€บ handbook โ€บ 2 โ€บ everyday-types.html
TypeScript: Documentation - Everyday Types
JavaScript has three very commonly used primitives: string, number, and boolean. Each has a corresponding type in TypeScript. As you might expect, these are the same names youโ€™d see if you used the JavaScript typeof operator on a value of those types:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ typescript โ€บ how-to-check-types-in-typescript
How to Check Types in Typescript? - GeeksforGeeks
July 23, 2025 - Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation.
๐ŸŒ
Allthingstypescript
allthingstypescript.dev โ€บ p โ€บ the-typeof-and-keyof-operators-referencing
The typeof and keyof operators - referencing variable types in Typescript
March 27, 2023 - As you can see, we created two Types - X and Y - and used the typeof operator to reference the types of variables x and y. And we can use it to reference types for all sorts of things - objects, arrays, object properties, etc. So far, so good. But we can do even better, and letโ€™s introduce another Typescript operator - the keyof operator.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-use-typeof-operator-in-typescript
How to use typeof operator in TypeScript?
January 3, 2023 - In TypeScript, the typeof is one of the most helpful operators and keywords to check the types of variables or identifiers. However, TypeScript is a type-strict language. So, we need to define the type of the variable or object while defining ...