Open In App

TypeScript Truthiness Narrowing Type

In this article, we are going to learn about Truthiness narrowing Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, truthiness narrowing is a concept that allows you to narrow down the type of a variable based on its truthiness (or falseness) in a conditional statement. It’s a type inference mechanism that takes advantage of JavaScript’s truthy and falsy values to determine the possible types of a variable.

Truthy Values: In JavaScript, values that are considered “truthy” are those that are treated as true when evaluated in a boolean context. These values include:



False Values: Conversely, “falsy” values are those that are treated as false in a boolean context. These values include:

Syntax:

if (condition) {
// Inside this block, TypeScript narrows the
// type of a variable.
} else {
// Inside this block, TypeScript knows
// something different about the variable.
}

Where-



Example 1: In the if block, TypeScript narrows down the type of name to string because it checks if name is truthy (i.e., not null or undefined). In the else block, TypeScript understands that name can only be null or undefined because it has already checked for truthiness




function greet(name: string | null) {
    if (name) {
        // In this block, TypeScript knows 
        // 'name' is a non-null string.
        console.log(`Hello, ${name.toUpperCase()}!`);
    } else {
        // In this block, TypeScript knows 
        // 'name' is either null or undefined.
        console.log("Hello, GeeksforGeeks!");
    }
}
  
greet("GeeksforGeeks");
greet(null);

Output:

Example 2: In this example, the printType function takes a parameter value. Inside the function, we use typeof to check the type of value. Depending on the type, TypeScript narrows the type of value inside each if block. This allows us to perform type-specific operations safely.




function printType(value: any) {
    if (typeof value === 'string') {
        console.log("It's a string:", value.toUpperCase());
    } else if (typeof value === 'number') {
        console.log("It's a number:", value.toFixed(2));
    } else {
        console.log("It's something else:", value);
    }
}
  
printType("Hello, GeeksforGeeks!");
printType(42);
printType(true);

Output:


Article Tags :