Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructuring with spread operator and typing

I have this object:

const ABCD = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}

I can destructure it, collect the rest of it using the "spread" operator, and type the variables like this:

const {a, b, ...restOfIt}: {a: number, b: number} = ABCD;

But how do I also type the restOfIt on the same line? The following all fail:

 const {a, b, ...restOfIt}: {a: number, b: number, ...restOfIt: any} = ABCD;
 const {a, b, ...restOfIt}: {a: number, b: number, restOfIt: any} = ABCD;

TypeScript playground here

like image 627
Marcus Junius Brutus Avatar asked Oct 18 '25 15:10

Marcus Junius Brutus


1 Answers

You can use dynamic key definition

const {a, b, ...restOfIt}: {a: number, b: number, [key: string]: any} = ABCD;

If you know all types in restOfIt is number, you also can use number instead of any which is better

const {a, b, ...restOfIt}: {a: number, b: number, [key: string]: number} = ABCD;

If you already have a type for restOfIt, you can use type union

type CD = {
  c: number,
  d: number
}
const {a, b, ...restOfIt}: { a: number, b: number} & CD = ABCD;

Playground

like image 199
Nick Vu Avatar answered Oct 22 '25 05:10

Nick Vu