0

In TypeScript, can I specify the type of the local variables created using the object rest/spread assignment feature? The problem is that the ES6 syntax obj: Type normally used by TypeScript to specify the type of a local variable is used in ES6 rest/spread definitions to refer to the name of the local variable(s) being defined if the name(s) are different from the object's property name(s). So how can I let TS know about the type that I'd like that variable to be?

For example, assume this code:

interface ABCD {
  a: string,
  b: number, 
  c: string, 
  d: number,
};
interface CD {
  c: string, 
  d: number,
};
const abcd: ABCD = {a: 'hello', b: 10, c: 'world', d: 20};
const {a, b, ...cd} = abcd;

Now if I wanted to specify that the variable cd should be type CD, how would I do it? The normal TS syntax for type specification below would define a new local variable CD.

const {a, b, ...cd: CD} = abcd;
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
Justin Grant
  • 44,807
  • 15
  • 124
  • 208
  • 1
    You can't specify the type in the spread expression. you can specify only whole type : `const { a, b, ...cd }: { a: string, b: number } & CD = abcd;` but that will not really impact the type of `cd` – Titian Cernicova-Dragomir Sep 30 '18 at 21:30
  • 1
    Good catch @Wing - sorry for duping the canonical question. Normally I'd delete mine, but leaving it here as a favor to future searchers who are looking for "rest" and "spread" and not "destructuring" as search keyword. – Justin Grant Sep 30 '18 at 22:49
  • Actually, the above statement is not true anymore. With TypeScript 3.0, you can. CORRECTION: that applies to array spread, not object spread. see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html – unional Oct 01 '18 at 04:48

0 Answers0