I have a method whose structure is given below.
const a = function (...args: any[]) {
console.log(args);
}
as you can see in the structure of the function, the type of args
is any[]
, I want to make a specific type for argument array accepted by the method.
How can I make a specific type for arguments accepted by the method in Typescript?
NOTE: The function a
can accept any type of argument like
a(1, 2, 4, 5, 'asgasg', 124.52, { name: 'sparsh' });
I want to make a specific type for arguments accepted by the method in Typescript.
CodePudding user response:
You can create a custom type:
type x = string | number
and in a case to fit your example:
type User = {
name: string;
}
type x = string | number | User;
function a(...args: x[]){}
CodePudding user response:
Instead of any[]
which would allow any property access including potentially invalid ones, one can use unknown[]
.
Using unknown[]
would allow passing any type of arguments, but will not disable type checking for property access etc. For example:
const a = function (...args: unknown[]) {
console.log(args);
// console.log(args[0].toString); //disallowed by type checking
if(typeof args[0] === 'number') console.log(args[0].toFixed()) //allowed
}
a(2,3,4,5,6,7,"asds"); //ok