I have a function which receives a variable number of arguments (each of type string), and a final argument (of a complex type, called Expression).
In JavaScript, this looks like:
function layerProp(...args) {
const fields = args.slice(0, -1)
const fallbackExpression = args.slice(-1)[0]
How can I write a type definition for this function?
4
Answers
For the function argument you can write as
...args: string[]
, From the function implementationfallbackExpression
is a simple string. So it would be better to use a interface instead of a typeYou can declare a union type like:
Then your code becomes:
If your method gets one complex
Expression
object, and a bunch of strings, you might want to consider flipping the positions of the arguments, and then you can do this:You can use the following type:
However, it won’t type the
slice
and the easiest solution would be just to assert the last element toExpression
as follows:Usage:
playground