[SOLVED] Typescript array destructuring type


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;


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

Answered By – Titian Cernicova-Dragomir

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *