How to check object type at runtime in TypeScript?

I am trying to find a way to pass an object to work and check its type at runtime. This is the pseudo code:

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

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

But typeof always returns “object”, and I could not find a way to get the real type “a” or “b”. The instance instance also did not work and returned the same. Any idea how to do this in TypeScript?

Thank you for your help !!!

+17
source share
4 answers

  : , , , , interface type. JavaScript instanceof , , TypeScript .

, .

, , , TypeScript , guard, true ( - ""). " arg is T), :

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

type-guard, , true false. , , , ( ), , . , , , .

+30

, . , .

:

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
}

:

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

+7

, typeof, undefined, :

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
0

OP " ".

- , - instanceof, , , .

, , , , .

, routerEvent NavigationStart

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

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

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

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

, NavigationStart | Cancel | Error.

instanceof Type Interface , ts JIT AOT. - , , JS.

-1
source

Source: https://habr.com/ru/post/1677574/


All Articles