1

Is there a way of getting the type of a variable in Typescript?

I know:

  1. typeof operator, but it only returns type in the primitive level, e.g. "string", "object", "boolean"

  2. instanceof only work for a class, when the variable is defined by let myVar = new Class()

  3. once compiled to javascript, these types and interfaces are gone, as they are only for Typescript to do static type-checking.

But if I have the following, how can I show a has a type of interface A?

interface A {
  title: string,
  description: string,
}

const a: A = { title: "my title", description: "my description" }

// cmd so it shows `a` is of `interface A`
console.log(...)

The reason I think there must be a way but just that I don't know how because a properly configured editor can show the variable type (at Typescript level) when the cursor is moved to the variable.

Thanks

Jimmy Chu
  • 972
  • 8
  • 27
  • 1
    No, this is impossible. You noted that "once compiled to javascript, these types and interfaces are gone, as they are only for Typescript to do static type-checking." So then, when console.log() runs in your JavaScript environment, then there is no such thing as A to be printed out. Your IDE knows the types because it has access to the TypeScript source code. That's not true of your runtime environment. – jcalz May 20 '22 at 03:51

0 Answers0