1

Suppose I have an interface MyInterface

Is there a native way in typescript to check if an object complies to MyInterface ?

Like instanceof but against an interface instead of a class.

Lev
  • 13,856
  • 14
  • 52
  • 84

2 Answers2

0

As far as I know there is no way, because I tried it several times with instanceof. It works for classes although.

So you have to check for the props of the object e.g.

if((object as SomeInterface).interfaceMethod)){
  // it's SomeInterface
} else {
  // it's not
}
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

There is no native way, but ts-interface-checker module can be used for runtime tests and validations.

It needs a runtime description of the interface, which can be built from the TypeScript interfaces in one step using the companion ts-interface-builder module.

DS.
  • 22,632
  • 6
  • 47
  • 54
  • I run `npm bin ts-interface-builder Widget_PieChartModel.ts` and nothing happening. i run the command from the folder where the file is ts located. Any clue @ds. Thanks for posting. – Abel Jojo Sep 14 '18 at 13:18
  • 1
    `npm bin` (No other args) gives the location of the executable files. Try it again with backticks as in README or run `node_modules/.bin/ts-interface-builder`. The output will be a new file next to the origiinal. – DS. Sep 15 '18 at 16:21
  • I opened bin folder in terminal and executed `ts-interface-builder E:....\PieChart\Widget_PieChartModel.ts` . @DS thank you – Abel Jojo Sep 17 '18 at 13:00
  • 1
    And do you see now a new file `E:....\PieChart\Widget_PieChartModel-ti.ts`? If yes, it can be used with `ts-interface-checker` module for runtime validations. If not, file a bug report at https://github.com/gristlabs/ts-interface-builder/issues with as much detail as possible. – DS. Sep 18 '18 at 16:20
  • I ti file is generated. I am using in condition checking. I few issue there. Let me try. thanks again @DS – Abel Jojo Sep 19 '18 at 05:14