blankface
blankface

Reputation: 6347

Check interface type in TypeScript

interface IData {
  firstName: string;
  lastName: string;
}

interface IDemo {
    Events: {
      GetItem: (callback: (data: IData) => void) => void;
    }
}

const item = {
  Events: {
    GetItem: //mock function
  }
}

if (item is of type IDemo)

In the above scenario, I have IDemo interface that takes in an object of Events, which in turn has an object called GetItem - a function.

I want to check if const item is of type IDemo. How can I achieve this?

Upvotes: 2

Views: 5885

Answers (1)

jh314
jh314

Reputation: 27792

Since item comes from ajax response, you are looking for some kind of runtime typecheck. TS interfaces are compile time entities, so you need to create your own runtime checks using your own type guard.

Something like:

function isIDemo(item: any): item is IDemo {
    return typeof item.first === 'string' && typeof item.last === 'string';
}

Upvotes: 3

Related Questions