TypeScript unknown Function
Last Updated :
18 Jul, 2024
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.
TypeScript
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.
TypeScript
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.