简体   繁体   中英

Check input obj type against custom interface in typescript

Is there a way to write a function in typescript like below. Where type T belongs to my custom interface.

checkType<T>(input):boolean{
   if(typeof input === T){
     return true;
   }
   else{
     return false;
   }
}

Actually I have 5 dropdowns and each dropdown gets bind to a different interface. On "selectionChange" event ( one event handler for all 5 dropdown), I have written below function and I am getting input as an json object which belongs to one of the interface,

public selectionChange(value: any): void {
    if(this.checkType<ICustomer>(value)){

      console.log("yes, this is a customer");

    }

but this is not working. can anyone suggest the better approach OR am I doing something wrong with the current approach.

This is not related to the typescript at all.

Typescript provides you only the transpilation-time control and it never ever throws any error in runtime and it does not do any special-checks (you can look to that transpiled code, it is very similar to original). Application is then using pure javascript and it is behaving as this.

The typeof is javascript keyword and even with typescript it will work just as in pure javascript. What you need can be done by creating instance of some class, you can get proper check with instanceof . Or you can have just some method, that finds out, what type you have based on some keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM