TypeScript unknown Function
Last Updated :
31 Oct, 2023
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!" );
}
}
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" ) {
return Math.PI * Math.pow(shape, 2);
} else if ( typeof shape === "object" && shape !== null ) {
if ( "width" in shape && "height" in shape) {
const rectangle =
shape as { width: number; height: number };
return rectangle.width * rectangle.height;
}
}
return undefined;
}
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
Share your thoughts in the comments
Please Login to comment...