Type Guards: in & instanceof
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 69 of 73.
When working with union types, you often need to determine which specific type you're dealing with before you can safely access type-specific properties or methods. Type guards provide a safe way to narrow down types at runtime.
The in operator checks whether a property exists on an object. This is particularly useful when you have a union of object types with different properties:
type Dog = { name: string; breed: string };
type Cat = { name: string; meow: () => void };
function petSound(pet: Dog | Cat) {
if ('breed' in pet) {
// TypeScript knows pet is a Dog here
console.log(`${pet.name} is a ${pet.breed}`);
} else {
// TypeScript knows pet is a Cat here
pet.meow();
}
}The instanceof operator checks if an object was created by a specific constructor function or class. While we haven't covered classes yet, this operator is useful when working with built-in JavaScript objects or custom classes:
function processValue(value: string | Date) {
if (value instanceof Date) {
// TypeScript knows value is a Date
console.log(value.getFullYear());
} else {
// TypeScript knows value is a string
console.log(value.toUpperCase());
}
}Both operators help TypeScript's compiler understand which type you're working with, enabling safe access to type-specific properties and methods.
Challenge
EasyCreate a function that processes different types of media items using the in operator to distinguish between them.
Create two type aliases:
Moviewith propertiestitle(string) anddirector(string)Songwith propertiestitle(string) andartist(string)
Create a function named getMediaInfo that:
- Takes a parameter
mediaof typeMovie | Song - Uses the
inoperator to check if thedirectorproperty exists - Returns
"Movie: [title] directed by [director]"if it's a movie - Returns
"Song: [title] by [artist]"if it's a song - Has an explicit return type of
string
Create a second function named processValue that:
- Takes a parameter
valueof typestring | Date - Uses the
instanceofoperator to check ifvalueis aDate - Returns the year as a number if it's a Date (using
getFullYear()) - Returns the string length as a number if it's a string
- Has an explicit return type of
number
Create test data:
movie1:{ title: "Inception", director: "Christopher Nolan" }song1:{ title: "Bohemian Rhapsody", artist: "Queen" }movie2:{ title: "The Matrix", director: "The Wachowskis" }song2:{ title: "Imagine", artist: "John Lennon" }testDate:new Date("2023-12-25")testString:"TypeScript"
Print the following outputs:
- Call
getMediaInfowithmovie1 - Call
getMediaInfowithsong1 - Call
getMediaInfowithmovie2 - Call
getMediaInfowithsong2 - Call
processValuewithtestDate - Call
processValuewithtestString
Try it yourself
// TODO: Write your code here
// Create type aliases for Movie and Song
// Create the getMediaInfo function
// Create the processValue function
// Create test data
const movie1 = { title: "Inception", director: "Christopher Nolan" };
const song1 = { title: "Bohemian Rhapsody", artist: "Queen" };
const movie2 = { title: "The Matrix", director: "The Wachowskis" };
const song2 = { title: "Imagine", artist: "John Lennon" };
const testDate = new Date("2023-12-25");
const testString = "TypeScript";
// Print the outputs
console.log(getMediaInfo(movie1));
console.log(getMediaInfo(song1));
console.log(getMediaInfo(movie2));
console.log(getMediaInfo(song2));
console.log(processValue(testDate));
console.log(processValue(testString));This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums11Advanced Topics
Type Assertions Type Guards: in & instanceofThe 'never' TypeNullable Types ('strictNull')Index Signatures for ObjectsRecap: Fine-Tuning Types3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples