2

How should I type following destructured array?

const [first, ...rest] = this.employee.roles;

The code above works, but project rules impose const typing.

I tried:

const first: Role;
const rest: Array<Role>;
[first, ...rest] = this.employee.roles;

but then I need to change const to let for [first, ...rest] = this.employee.roles; to work

Following code also works, but isn't it misleading?

const [first, ...rest]: Array<Role> = this.employee.roles;

since first is Role and rest is Array<Role> I'm not sure about this one.

I'd like something similar to this:

const [first, ...rest]: [first: Role, rest: Array<Role>] = this.employee.roles;

but it's not compiling.

Is there a clean way of typing this or should I just switch to

let first: Role;
let rest: Array<Role>;
[first, ...rest] = this.employee.roles;
2
  • 1
    i think your first idea is correct: const [first, ...rest]: Array<Role> = this.employee.roles; (try console logging [first, ...rest] out) Commented Mar 17, 2022 at 9:46
  • 1
    if this.employee.roles is already typed, the type of first and rest should be inferred correctly. if you really need to specify it, this const [first, ...rest]: Array<Role> = this.employee.roles; looks correct to me aswell Commented Mar 17, 2022 at 10:11

1 Answer 1

2

I would just use onst [first, ...rest]: Array<Role>. If you want you can type is with tuple types, but you will have to make first optional, since there is no guarantee Role[] will contain any elements, it could be empty:


const [first, ...rest]: [first?: Role, ...rest: Array<Role>] = roles;

Playground Link

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.