1

i want to remove the first array element, without modified the original (immutable),
something like this:

function getArray(): number[] {
   return [1, 2, 3, 4, 5];
}
function getAnother(): number[] {
   const [first, ...rest] = getArray();
   return rest;
}

the code works, but the typescript check complained:

'first' is assigned a value but never used  @typescript-eslint/no-unused-vars

Is there the elegant/better way to do somilar to getAnother()?

2
  • arr.slice(1)? Commented Jul 23, 2021 at 19:22
  • Also, it's not the typescript check that complains, this is an ESLint rule. As with literally any ESLint rule, you can adjust it or disable it (even locally). Commented Jul 23, 2021 at 19:24

3 Answers 3

3

You can ignore an element with a comma.

 const [, ...rest] = getArray();

Array#slice can also be used in this case.

const rest = getArray().slice(1);
Sign up to request clarification or add additional context in comments.

1 Comment

@HeyyyMarco Happy to help.
1

You can use default Array method

Array.prototype.slice

Try this

function getAnother(): number[] {
    return getArray().slice(1)
}

Comments

1

One common practice here is to prefix unused variables or arguments with an underscore, as in one of the following:

const [_first, ...rest] = getArray();
const [_, ...rest] = getArray();

This allows you to still use a visible or labeled placeholder. Though this works without configuration in Visual Studio Code's syntax highlighting, you may need to configure it for your ESLint usage with varsIgnorePattern and argsIgnorePattern, which in ESLint is suggested in documentation as "^_".

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.