0

I'm new to typescript, with a javascript background.

In (modern) js, the following is possible:

 let {n,s} = {n:42, s:'test'};
 console.log(n, s); // 42 test

In typescript I was assuming I could do the same, and indeed, according to the docs both declarations and assignments support destructuring. Except I can't seem to make it work:

let {n:number, s:string} = {n:42, s:'test'}; // All destructured elements are unused.
console.log(n, s); // Cannot find name 'n' (nor 's')

What did I miss ?

Antoine
  • 13,494
  • 6
  • 40
  • 52
  • 1
    The code at the top works in both JS and TS. The code at the bottom is assigning to different variables in both JS and TS, not doing a type annotation. You have to annotate the whole object, not the destructured variables, if you want to do it. Like [this](http://www.typescriptlang.org/play//#code/DYUwLgBA3hB2A0EDOEC+EC804C4IBYAmRJPAcjBCTDLQG4IBYAKFEhlgWRVTw9jywArgFsARiABOJUsjCSAlrADmaTNk54iMvACJK1XfRZA) (`let {n, s}: {n: number, s: string} = {n: 42, s: 'test'};`). – jcalz Nov 25 '19 at 15:47
  • Ok thanks, I can accept that as an answer if you make one – Antoine Nov 25 '19 at 15:53

1 Answers1

1

I don't think the above is valid syntax. If you run the above on the TypeScript playground, you will realise it is invalid syntax. When it comes to TypeScript, destructruing works the exact same way as JavaScript.

What I would recommend, would be to provide proper typings (perhaps using an interface) for your object, before destructuring it.

interface Item {
  n: number;
  s: string;
}

const item: Item = {
  n: 42, 
  s: 'test',
}

let { n, s } = item;
console.log(n, s);

The destructured elements will automatically infer the types from your initial object.

wentjun
  • 40,384
  • 10
  • 95
  • 107