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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With