Home > database >  Typescript is it possible to know the exactly class of an object when using a variable that has a un
Typescript is it possible to know the exactly class of an object when using a variable that has a un

Time:06-26

I am studying Typescript, and performing some tests. console.log gives me an object. If Typescript is typed I would expect it know the type of the variable c exactly.

interface Car {
  gears: number
}

interface Bike{
  gears: number,
  model: string
}

let c: Bike | Car;

c = {gears : 2};

console.log(typeof c);

CodePudding user response:

TS keeps type information only at compile time. Type information is discarded at run time.

Even more, typeof is a JS method and as such will operate as JS not TS.

You can look over the return values of typeof here. TS docs also confirm this.

What you probably want is look into narrowing as there a lot of ways to to "type checking".

Keep in mind that TS uses structural typing as opposed to nominal typing (as C#/Java do). This means that 2 object don't need to have the same type, they just need to be compatible enough (this usually means having enough methods/fields to overlap).

CodePudding user response:

typeof is a JavaScript operator that gives you the type of a given variable on runtime, while types you define with TypeScript exist only while writing your code and while compiling. On runtime you have only native JavaScript types which are: Boolean, Null, Undefined, Number, BigInt, String, Symbol and Object.

That has been said, to distinguish between Car and Bike while using them as a union type, a commun way is to have a discriminator property. Like so:

interface Car {
  gears: number,
  type:"car"
}

interface Bike{
  gears: number,
  model: string,
  type:"bike"
}

// to show an use case
function foo(bar: Car | Bike ) {
  if(bar.type === "bike"){
    // only here TypeScript would let acces model propriety 
    console.log(bar.model); 
  }
}
  • Related