4
interface SStitle {
  title: string;
  }
  const x:SStitle = { title: "AZ5"};

  if(???){...}esle{...} //x === SStitle

I have an interface SStitle.I want to write in if (???) such logic that type X is compared with type SStitle.

  • 3
    Possible duplicate of [How to check the object type on runtime in TypeScript?](https://stackoverflow.com/questions/44078205/how-to-check-the-object-type-on-runtime-in-typescript) – Willis Blackburn Jul 02 '19 at 02:42

1 Answers1

2

Here is one important thing to note. Typescript defines types (with interface and type keywords). And as TS is compiled to JavaScript, types are completely removed from output JS file.

So to make sure that x is of type SStitle in run time, we should rely on some properties of SStitle which will be preserved after compilation.

In TS this is achieved using type guards.

So your code with type guard will look like

interface SStitle {
    title: string;
}
const x: SStitle = { title: "AZ5" };

// This function is type guard, which works during compilation and during run time.
function isSStitle (x: any): x is SStitle {
    return x.title !== undefined;
}

if (isSStitle(x)) {
    console.log("x is SStitle");
} else{
    console.log("x is NOT SStitle");} 
Fyodor Yemelyanenko
  • 11,264
  • 1
  • 30
  • 38