Open In App

TypeScript unknown Function

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, the unknown type is used for variables whose type is not known in advance. It provides type safety by requiring explicit type checks or assertions before using the value, ensuring safe and controlled handling of uncertain data types. It is similar to any type in that it can hold values of any type, but it is more type-safe. Unlike any, you cannot perform arbitrary operations on values of type unknown without first narrowing or asserting the type

Syntax

function gfg(input: unknown): void {
}

Parameters

  • gfg: This represents the name of the function.
  • input: This represents the name of the parameter passed to the function.
  • unknown: This represents the type of parameter passed.
  • void: This represents the return type of the function.

Example 1: In this example, The greet function accepts an unknown parameter name and handles different types: strings get personalized greetings, null is a special case, and other types receive a generic greeting. It demonstrates flexible typing and type checks for safe behavior.

Javascript




function greet(name: unknown): void {
    if (name === null) {
        console.log("null!");
    } else if (typeof name === "string") {
        console.log(`Hello, ${name}!`);
    } else {
        console.log("Hello, guest!");
    }
}
  
// Calling the greet function with different arguments
greet("GeeksforGeeks");
greet(44);
greet(null);


Output:

Hello, GeeksforGeeks!
Hello, guest!
null!

Example 2: in this example, The calculateArea function handles various shapes or values by type checking. It calculates circle or rectangle areas based on input type. If unrecognized, it returns undefined. Calls with circles, rectangles, or other shapes yield appropriate results.

Javascript




function calculateArea(shape: unknown): number | undefined {
    if (typeof shape === "number") {
      
        // If the input is a number, assume 
        // it's the radius of a circle
        return Math.PI * Math.pow(shape, 2);
    } else if (typeof shape === "object" && shape !== null) {
      
        // If the input is an object 
        //(potentially representing a rectangle)
        if ("width" in shape && "height" in shape) {
          
            // Check if it has width and height properties
            const rectangle =
                shape as { width: number; height: number };
            return rectangle.width * rectangle.height;
        }
    }
  
    // If the input doesn't match any 
    //recognized shape, return undefined
    return undefined;
}
  
// Calling the calculateArea function
// with different arguments
console.log(calculateArea(5));
console.log(calculateArea({ width: 4, height: 6 }));
console.log(calculateArea({ length: 7 }));


Output:

78.53981633974483
24
undefined

Reference: https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads