If you want to use Type union in many places within your TypeScript program then it is better to use Type aliases to replace it instead. The below program is exactly the same as the previous one except for this time I am using Type aliases to replace all those type union parameters within the header of the ‘objtype’ function.
type stringnumberboolean = string | number | boolean function objtype(obj : stringnumberboolean) { if(typeof obj == "string") { console.log(`${obj} is a string`) } else if(typeof obj == "number") { console.log(`${obj} is a number`) } else { console.log(`${obj} is a boolean`) } } objtype(3) objtype("Hello World") objtype(true)
With a simple type aliases declaration on top of the typescript function as follows:-
type stringnumberboolean = string | number | boolean
You can then use the type aliases named stringnumberboolean everywhere within the header of the above function.