Open In App

TypeScript Other Types to Know About

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:

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.


Article Tags :