How to check the object type on runtime in TypeScript?

TypescriptTypesRuntime

Typescript Problem Overview


I'm trying to find a way to pass an object to function in and check it type in a runtime. This is a pseudo code:

function func (obj:any) {
    if(typeof obj === "A") {
        // do something
    } else if(typeof obj === "B") {
        //do something else
    }
}

let a:A;
let b:B;
func(a);

But typeof always returns "object" and I could not find a way to get the real type of a or b. instanceof did not work either and returned the same.

Any idea how to do it in TypeScript?

Typescript Solutions


Solution 1 - Typescript

> Edit: I want to point out to people coming here from searches that this question is specifically dealing with non-class types, ie object > shapes as defined by interface or type alias. For class types you > can use JavaScript's instanceof to determine the class an instance comes from, and TypeScript will narrow the type in the type-checker automatically.

Types are stripped away at compile-time and do not exist at runtime, so you can't check the type at runtime.

What you can do is check that the shape of an object is what you expect, and TypeScript can assert the type at compile time using a user-defined type guard that returns true (annotated return type is a "type predicate" of the form arg is T) if the shape matches your expectation:

interface A {
  foo: string;
}

interface B {
  bar: number;
}

function isA(obj: any): obj is A {
  return obj.foo !== undefined 
}

function isB(obj: any): obj is B {
  return obj.bar !== undefined 
}

function func(obj: any) {
  if (isA(obj)) {
    // In this block 'obj' is narrowed to type 'A'
    obj.foo;
  }
  else if (isB(obj)) {
    // In this block 'obj' is narrowed to type 'B'
    obj.bar;
  }
}

Example in Playground

How deep you take the type-guard implementation is really up to you, it only needs to return true or false. For example, as Carl points out in his answer, the above example only checks that expected properties are defined (following the example in the docs), not that they are assigned the expected type. This can get tricky with nullable types and nested objects, it's up to you to determine how detailed to make the shape check.

Solution 2 - Typescript

Expanding on Aaron's answer, I've made a transformer that generates the type guard functions at compile time. This way you don't have to manually write them.

For example:

import { is } from 'typescript-is';

interface A {
  foo: string;
}

interface B {
  bar: number;
}

if (is<A>(obj)) {
  // obj is narrowed to type A
}

if (is<B>(obj)) {
  // obj is narrowed to type B
}

You can find the project here, with instructions to use it:

https://github.com/woutervh-/typescript-is

Solution 3 - Typescript

The OPs question was "I'm trying to find a way to pass an object to function in and check it type in a runtime".

Since a class instance is just an object the correct answer is to use a class instance and instanceof when runtime type checking is needed, use interface when not.

In my codebase, I will typically have a class which implements an interface and the interface is used during compilation for pre-compile time type safety, while classes are used to organize my code as well as do runtime type checks in typescript.

Works because routerEvent is an instance of NavigationStart class

if (routerEvent instanceof NavigationStart) {
  this.loading = true;
}

if (routerEvent instanceof NavigationEnd ||
  routerEvent instanceof NavigationCancel ||
  routerEvent instanceof NavigationError) {
  this.loading = false;
}

Will not work

// Must use a class not an interface
export interface IRouterEvent { ... }
// Fails
expect(IRouterEvent instanceof NavigationCancel).toBe(true); 

Will not work

// Must use a class not a type
export type RouterEvent { ... }
// Fails
expect(IRouterEvent instanceof NavigationCancel).toBe(true); 

As you can see by the code above, classes are used to compare the instance to the types NavigationStart|Cancel|Error.

Using instanceof on a Type or Interface is not possible since the ts compiler strips away these attributes during its compilation process and prior to being interpreted by JIT or AOT. Classes are a great way to create a type which can be used precompilation as well as during the JS runtime.

Solution 4 - Typescript

I've been playing around with the answer from Aaron and think it would be better to test for typeof instead of just undefined, like this:

interface A {
  foo: string;
}

interface B {
  bar: number;
}

function isA(obj: any): obj is A {
  return typeof obj.foo === 'string' 
}

function isB(obj: any): obj is B {
  return typeof obj.bar === 'number' 
}

function func(obj: any) {
  if (isA(obj)) {
    console.log("A.foo:", obj.foo);
  }
  else if (isB(obj)) {
    console.log("B.bar:", obj.bar);
  }
  else {console.log("neither A nor B")}
}

const a: A = { foo: 567 }; // notice i am giving it a number, not a string 
const b: B = { bar: 123 };

func(a);  // neither A nor B
func(b);  // B.bar: 123

Solution 5 - Typescript

No, You cannot reference a type in runtime, but yes you can convert an object to a type with typeof, and do validation/sanitisation/checks against this object in runtime.

const plainObject = {
  someKey: "string",
  someKey2: 1,
};
type TypeWithAllOptionalFields = Partial<typeof plainObject>; //do further utility typings as you please, Partial being one of examples.

function customChecks(userInput: any) {
  // do whatever you want with the 'plainObject'
}

Above is equal as

type TypeWithAllOptionalFields = {
  someKey?: string;
  someKey2?: number;
};
const plainObject = {
  someKey: "string",
  someKey2: 1,
};
function customChecks(userInput: any) {
  // ...
}

but without duplication of keynames in your code

Solution 6 - Typescript

You can call the constructor and get its name

let className = this.constructor.name

Solution 7 - Typescript

> I know this is an old question and the "true" question here is not the > same as the question in the title, but Google throws this question for > "typescript runtime types" and some people may know what they are > looking for and it can be runtime types. > > Right answer here is what Aaron Beall answered, the type guards. > > But answer, matching question in the title and matching Google > searches, is only usage of TypeScript transformers/plugins. TypeScript > itself strip out information about types when transpiling TS to JS. > And well,.. it is one of the possible ways how to implement the type guards, > eg. the typescript-is transformer as user7132587 pointed out.

Another options is transformer tst-reflect. It provides all the information about types at runtime. It allows you to write own type guards based on type information, eg. checking that object has all the properties you expect. Or you can use directly Type.is(Type) method from the transformer, which is based directly on the TypeScript's type checking information.

I've created this REPL. Have a fun! More info in Github repository.

import { getType, Type } from "tst-reflect";

class A {
  alphaProperty: string;
}

interface B {
  betaProperty: string;
}

class Bb extends A implements B {
  betaProperty = "tst-reflect!!";
  bBetaProperty: "yes" | "no" = "yes";
}

/** @reflectGeneric */
function func<TType>(obj?: TType) 
{
    const type: Type = getType<TType>();

    console.log(
      type.name, 
      "\n\textends", type.baseType.name,
      "\n\timplements", type.getInterface()?.name ?? "nothing",
      "\n\tproperties:", type.getProperties().map(p => p.name + ": " + p.type.name),
      "\n"
    );
    
    console.log("\tis A:", type.is(getType<A>()) ? "yes" : "no");
    console.log("\tis assignable to A:", type.isAssignableTo(getType<A>()) ? "yes" : "no");
    console.log("\tis assignable to B:", type.isAssignableTo(getType<B>()) ? "yes" : "no");
}

let a: A = new A();
let b: B = new Bb();
let c = new Bb();

func(a);
func<typeof b>();
func<Bb>();

Output:

A 
    extends Object 
    implements nothing 
    properties: [ 'alphaProperty: string' ] 

    is A: yes
    is assignable to A: yes
    is assignable to B: no
B 
    extends Object 
    implements nothing 
    properties: [ 'betaProperty: string' ] 

    is A: no
    is assignable to A: no
    is assignable to B: yes
Bb 
    extends A 
    implements B 
    properties: [ 'betaProperty: string', 'bBetaProperty: ' ] 

    is A: no
    is assignable to A: yes
    is assignable to B: yes

Solution 8 - Typescript

Alternative approach without the need of checking the type

What if you want to introduce more types? Would you then extend your if-statement? How many such if-statements do you have in your codebase?

Using types in conditions makes your code difficult to maintain. There's lots of theory behind that, but I'll save you the hazzle. Here's what you could do instead:

Use polymorphism

Like this:

abstract class BaseClass {
    abstract theLogic();
}

class A extends BaseClass {
    theLogic() {
       // do something if class is A
    }
}


class B extends BaseClass {
    theLogic() {
       // do something if class is B
    }
}

Then you just have to invoke theLogic() from whichever class you want:

let a: A = new A();
a.theLogic();

let b: B = new B();
b.theLogic();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEden1971View Question on Stackoverflow
Solution 1 - TypescriptAaron BeallView Answer on Stackoverflow
Solution 2 - Typescriptuser7132587View Answer on Stackoverflow
Solution 3 - TypescriptAlpha G33kView Answer on Stackoverflow
Solution 4 - TypescriptCarl SorensonView Answer on Stackoverflow
Solution 5 - TypescriptkairunView Answer on Stackoverflow
Solution 6 - TypescriptShady SmaouiView Answer on Stackoverflow
Solution 7 - TypescriptHookynsView Answer on Stackoverflow
Solution 8 - TypescriptStefan WoehrerView Answer on Stackoverflow