Home > Software engineering >  How to check if a class has been declared in Typescript?
How to check if a class has been declared in Typescript?

Time:04-11

Javascript has a convenient way to check if a class (or any other) exists in the global scope:

typeof SomeUndeclaredOne === 'undefined'

This method doesn't work in typescript because it produces a compilation error:

error TS2304: Cannot find name 'SomeUndeclaredOne'

So my question is: what is the easiest way to check if a class exists in a typescript? I'm looking for a generic way that works not only in browsers but also other environments (e.g. node.js or other environments that don't have a global object) and works with popular module systems (like ESModules, CommonJS) too.

Thanks in advance for any advice.

CodePudding user response:

You could declare the class with TypeScript to get rid of the error.

declare class SomeUndeclaredOne {}
console.log(typeof SomeUndeclaredOne === "undefined")
  • Related