K
K
Kolabrod2021-09-23 13:54:32
typescript
Kolabrod, 2021-09-23 13:54:32

How to type the input parameters of a function, which can change during the check?

there is some function that can take an object or an array of these objects.
on initial argument check, if not an array wraps the object in an array.
ts swears at the whole thing.
Whether probably this business to make friends without the declaration of a new variable?

fn(x: any, y: any, z: any):any{
    if (!Array.isArray(x)) x = [x];
    if (!Array.isArray(y)) y = [y];
    if (!Array.isArray(z)) z = [z];
// .....
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-09-23
@vabka

For example:

function fn(x: number | Array<number>): void {
    if(!Array.isArray(x))
        x = [x];
    console.log(x);
}

In your code, the compiler most likely swears that xs is not declared anywhere

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question