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 ?
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.
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 ();
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.
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:
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 {
....
}
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 => { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With