What are Type Predicates in TypeScript?
A type predicate is a function that returns a boolean, showing whether a variable is of a specific type.
Syntax:
ts
function isType(arg: any): arg is Type {// logic to check if arg is of Type}
Here, arg is Type
is the type predicate. It tells TypeScript that if the function returns true
, arg
is of type Type
.
Examples:
Ensuring Data Integrity in API Responses
When dealing with API responses, the data might not always be in the expected format. For example, if we get user data from an API, we need to make sure it matches our User
interface before using it.
ts
interfaceUser {id : number;name : string;}functionisUser (data : any):data isUser {return (data &&typeofdata === "object" &&"id" indata &&typeofdata .id === "number" &&"name" indata &&typeofdata .name === "string" &&"email" indata &&typeofdata .);}// Simulated API responseconstapiResponse : any = {id : 1,name : "Jack Black",};if (isUser (apiResponse )) {// TypeScript now knows that 'apiResponse' is a 'User'console .log (`User: ${apiResponse .name }`);} else {console .error ("Invalid user data");}
This example shows how type predicates make sure the API response matches the User
structure before doing anything with it, preventing possible runtime errors.
Handling Different Event Types in Event Listeners
When handling different event types, it's important to know the exact type of event to handle it properly. For example, if we have a system that logs various events like ClickEvent
and KeyboardEvent
.
ts
interfaceClickEvent {type : "click";x : number;y : number;}interfaceKeyEvent {type : "keyboard";keystroke : string;}typeEventType =ClickEvent |KeyEvent ;functionisClickEvent (event :EventType ):event isClickEvent {returnevent .type === "click";}functionisKeyboardEvent (event :EventType ):event isKeyEvent {returnevent .type === "keyboard";}functionhandleEvent (event :EventType ) {if (isClickEvent (event )) {console .log (`Click at coordinates: (${event .x }, ${event .y })`);} else if (isKeyboardEvent (event )) {console .log (`Key pressed: ${event .keystroke }`);} else {console .log ("Unknown event type");}}// Simulated eventsconstevents :EventType [] = [{type : "click",x : 100,y : 200 },{type : "keyboard",keystroke : "Enter" },];events .forEach (handleEvent );
This example shows how type predicates can help handle different event types correctly, making sure the right logic is used based on the event type.