3

I've got a class that inherits from Array:

class List<T> extends Array<T> {
    constructor(items: T[]) {
        super(items); // error here...
    }
}

Argument of type 'T[]' is not assignable to parameter of type 'T'.

Assuming this is because Array's constructor takes (...items: T[])

So, how do I pass a standard array to something that takes a spread operator?

1 Answer 1

3

The Array Constructor takes any number of parameters. If you pass in an array into new Array() it gets assigned to the first index.

const newArray = new Array([1, 2, 3]);
console.log(newArray); // [[1, 2, 3]];

Use the spread operator to expand the array out to the parameters.

const newArray = new Array(...[1, 2, 3]); // equivalent to new Array(1, 2, 3);
console.log(newArray); // [1, 2, 3];

So your class would look like this:

class List<T> extends Array<T> {
    constructor(items: T[]) {
        super(...items); // Spread operator here
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.