Sometimes, we want to specify parameter type as one of many types instead of any type in TypeScript.
In this article, we’ll look at how to specify parameter type as one of many types instead of any type in TypeScript.
How to specify parameter type as one of many types instead of any type in TypeScript?
To specify parameter type as one of many types instead of any type in TypeScript, we can create a union type.
For instance, we write
const myFunc = (param: string[] | boolean[] | number[]): void => {
//...
};
to create the myFunc
function that takes the param
parameter which can either be a string arrat, number array or boolean array.
And the return type is void
so it returns nothing.
Conclusion
To specify parameter type as one of many types instead of any type in TypeScript, we can create a union type.