TypeScript Other Types to Know About describes that there are many other types that can be used in various ways. like void, object, unknown, never, and function, and how they can be used to enhance the functionality of your code.
Other types to know about:
- void: In TypeScript, a void function is a function that doesn’t return any value, or returns undefined.
- object: Object Literals are typically defined as a set of name-value pairs stored in comma-separated lists.
- unknown: 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.
- never: In TypeScript, the never type is a function that never returns a value but throws an exception or error and terminates the program. It is often used to indicate that a function will not return a value or that a variable will never have a value.
-
function: Functions in TypeScript represent blocks of code that can be executed and can possess properties like
bind
,call
, andapply
. They’re versatile as they can be called and can return different types of values, includingthis
others.
Example 1: In this example, we are creating a function that takes a parameter of type string and returns void.
function greet(name: string): void {
console.log(`Hello, ${name}!!`);
} greet( "GeeksforGeeks" )
|
Output:
Hello, GeeksforGeeks!!
Example 2: In this example, we are creating an object giving it a key-value pair, and printing the result in the console.
let Employee_details = { Empname: "John" ,
EmpSection: "field"
} console.log( "Employee Name is:" +
Employee_details.Empname +
" Employee's section is:"
+ Employee_details.EmpSection
); |
Output:
Employee Name is:John Employee's section is:field
Example 3: In this example, we are creating a function that is taking a parameter of unknown type which means it can accept any type of data.
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!
Conclusion: In this article, we have discussed about the other types which can be used to write code in efficient way. also, we have seen descriptive explanation of each of them and some examples.