0

Given this example, I am trying to figure how to cast an Object to an interface (or a class):

interface Person {
  firstName: string;
  lastName:  string;
}
 
var obj={firstName:"James", lastName:"Bond"} as Person;
 
console.log(typeof(obj));

I've tried class too, but the console is still showing as "object" or false, in this case I am expecting a "Person", when using class I have tried obj instanceof Person, which return's false

Zulander
  • 648
  • 1
  • 10
  • 22
  • In addition to what @Quentin said ... you can find documentation on `typeof` here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#description In the description, it states that the table summarizes all possible return values of typeof. – DeborahK Jul 07 '23 at 22:27
  • Check out this article for additional suggestions: https://stackoverflow.com/questions/7893776/the-most-accurate-way-to-check-js-objects-type – DeborahK Jul 07 '23 at 22:37

2 Answers2

1

TypeScript definitions are used purely at compile time (and by linters before compile time).

After the code is converted to JavaScript, so it can run in Node.js or a browser, the types no longer exist.

Zze
  • 18,229
  • 13
  • 85
  • 118
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Why does when you debug using the console of Chrome, it's show' the name of the class when creating new Person(...) but when you cast it show's as an Object... – Zulander Jul 07 '23 at 22:00
  • A JavaScript class isn't the same thing as a TypeScript interface. – Quentin Jul 07 '23 at 22:02
0

There are only a handful of primatives in JS (see here) so almost everything is an object.

Under the hood, there do not exist classes in JS. Rather, JS achieves the same thing with prototypical inheritance.

An interface is something that only exists in TS (not JS) which, as detailed in the previous answer, does not exist as runtime (which is only JS).

I think there are a limited number of situations which require the use of classes in TS (library code when builder pattern is used such as in zod or trpc is a great use case). If there are no methods to be defined, just use a type!

I have made this TS Playground to demonstrate some of the roughly equivalent ways of declaring and consuming an object in TS. I would pay particular attention to the output JS (.js) and type declaration files (.d.ts) which may help to demonstrate what TS does.