Open In App

TypeScript unknown Function

Last Updated : 18 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In TypeScript, the unknown type is used for variables whose types aren't known in advance. It ensures type safety by requiring explicit type checks or assertions before usage, preventing arbitrary operations, and promoting safer handling compared to the `any` 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: Greeting Function with unknown Type

This example demonstrates a function that accepts an unknown parameter and handles different types. Strings get personalized greetings, null is a special case, and other types receive a generic greeting.

function greet(name: unknown): void {
    if (typeof name === "string") {
        console.log(`Hello, ${name}!`);
    } else if (name === null) {
        console.log("Hello, guest!");
    } else {
        console.log("Hello, there!");
    }
}


greet("GeeksforGeeks"); 
greet(null);           
greet(42);             

Output:

Hello, GeeksforGeeks!
Hello, guest!
Hello, there!

Example 2: Calculating Area with unknown Type

This example demonstrates a function that handles various shapes or values by type checking. It calculates circle or rectangle areas based on the input type. If unrecognized, it returns undefined.

type Circle = { radius: number };
type Rectangle = { width: number, height: number };

function calculateArea(shape: unknown): number | undefined {
    if (typeof shape === "object" && shape !== null) {
        if ("radius" in shape) {
            return Math.PI * (shape as Circle).radius ** 2;
        } else if ("width" in shape && "height" in shape) {
            return (shape as Rectangle).width * (shape as Rectangle).height;
        }
    }
    return undefined;
}


console.log(calculateArea({ radius: 5 }));
console.log(calculateArea({ width: 4, height: 6 }));
console.log(calculateArea("random shape"));         

Output:

78.53981633974483
24
undefined

Conclusion

The unknown type in TypeScript enhances type safety by requiring explicit type checks or type assertions before using the variable. It prevents arbitrary operations on values of uncertain types, promoting safer and more robust code.

FAQs-TypeScript unknown Function

How does unknown differ from any in TypeScript?

The unknown type is safer than any because it does not allow arbitrary operations without type checks. With any, you can perform any operation without type safety, which can lead to runtime errors.

Why should you use unknown instead of any?

unknown enforces type checks and assertions, leading to safer and more predictable code. It helps prevent runtime errors by ensuring you handle different types correctly.

How does TypeScript's type inference work with unknown types?

TypeScript does not infer the type of a value declared as unknown. Instead, it requires explicit type checks or assertions to narrow down the type. This ensures that the developer consciously determines the value's type before using it.

What are common use cases for the unknown type?

Common use cases include handling inputs where the type is not known upfront, such as user inputs, API responses, or data from external sources.

What are the differences between unknown and any in terms of operations?

With any, you can perform any operation without type checking, potentially leading to runtime errors. With unknown, TypeScript forces you to check or assert the type before performing operations, preventing unsafe operations and improving reliability.


Next Article

Similar Reads

three90RightbarBannerImg