Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add types to `...args` in typescript

I have a function like this

function foobar(...args): any {
    ....
}

The function signature is rather general, but it only accepts strings and an last an object of type X (all being optional)

foobar();
foobar('a');
foobar('a', 'b', 'c');
foobar('a', { ... });
foonbar('a', 'b', { ... }); 

Is there some way that types can be added, for example

function foobar(...args: [...string, X]) {  // this doesn't work!

}

Any suggestions ?

like image 345
Jeanluca Scaljeri Avatar asked Nov 10 '17 08:11

Jeanluca Scaljeri


People also ask

Why do I get function arguments errors in typescript?

In TypeScript, the compiler checks every function call and issues an error in the following cases: The number of arguments is different from the number of parameters specified in the function. Or the types of arguments are not compatible with the types of function parameters.

How do you create a class type in typescript using generics?

Using Class Types in Generics. When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. For example, function create < Type > ( c: { new (): Type }): Type {. return new c ();

Why create custom types in typescript?

Creating your own custom types to represent the data structures used in your own code can provide a flexible and useful TypeScript solution for your project.

Why does typescript throw an error when creating an object?

When creating an object with the custom type Programmer, if you assign a value with an unexpected type to any of the properties, TypeScript will throw an error. Take the following code block, with a highlighted line that does not adhere to the type declaration:


2 Answers

You can set any type you want for the ...args spread argument but it has to be an array of something

i.e.

function foobar(...args: string[]): any {
    ....
}

In your case there is no way to specify a certain type for the last object but you could do something like

function foobar(...args: Array<string | IYourCustomType>): any {
    ....
}

In general it is common practice to put the fixed arguments first and the optional arguments last so I would rewrite the function as

function foobar(obj: IYourCustomType, ...args: string[]): any {
    ....
}
like image 119
klugjo Avatar answered Oct 17 '22 23:10

klugjo


There have been since been improvements with typescript ability to type a tuple. You can now type each element uniquely. Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html

function getSomething(tuple: [string, boolean]): any => { ... }
like image 28
tpdietz Avatar answered Oct 18 '22 00:10

tpdietz