Reputation:
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.
Upvotes: 4
Views: 68
Reputation: 11848
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");}
Upvotes: 2