Open In App

TypeScript Creating Types from Utility Type

TypeScript Creating Types from Utility Type increases the code readability and ease of use when using any complex operations and values, there are different ways to do the type creation with the existing ones.

TypeScript Creating Types from Utility Type:

Example 1: In this example, we will use the keyof operator. The keyof operator takes an object and produces a string or numeric literal as a resultant type that describes every possible string or numeric key that can be present in the string.






// The keyof operator example
 
type object_type0 = { val1: string, val2: number }
 
// Accepts only val1 and val2 as key
// equivalent to T0 = val1 | val2
type T0 = keyof object_type0;
 
const result: object_type0 = { val1: "hello", val2: 32 };
console.log(result)

Output:

 {   "val1": "hello",   "val2": 32 } 

Example 2: In this example, we will use the typeof operator to get the type from a value and pass it to a utility type to get the desired output type.






console.log(typeof 'Hello typeof operator')
 
// A simple function which accepts two number
// Adds and return the resultant number
function add(arg1: number, arg2: number): number {
    return arg1 + arg2;
 
}
 
// The typeof is used to get the result type.
type addResultType = ReturnType<typeof add>;
 
let val1: number = 3;
let val2: number = 8;
 
// The result type is used for type safety
let sumVal: addResultType = add(3, 8)
console.log(sumVal)

Output:

string
11

Conclusion: By using the above features, typescript can help us to elevate the simplicity and power of creating types from existing types, starting off from generics, keyof operator, fetching types from values using typeof operator, conditionally using the types, mapped types and much more.


Article Tags :