Tuesday, 4 September 2018

Destructuring assignments in TypeScript

This is a really quick post to show some examples of destructuring assignments in TypeScript.

First, what is a destructuring assignment in JavaScript?


Basically when you want to assign some data from an array or object into separate variables.

// from an object to a variable
let obj = {foo: 13, bar: 'baz'}; // get the object

let {foo, bar} = obj; // get two variables out of the object

// from an array
let arr = [1, 2, 3, 4]; // get the array
let [a, b, ...others] = arr; // get three variables out of the array

If that's confusing, the MDN link above will explain everything!

The above JavaScript will compile as TypeScript as well, but sometimes when you define a function, there is no type for the parameters yet, so they become 'any'.


// objects
func({a, b}) { ... } // a and b would be 'any'

func({a, b}: {a: number, b: string} { ... } // now a and by have types!

// arrays

func([a, b]: [number, string]) { ... } // a and by have types!

There is more great info here.

No comments:

 
Copyright 2009 Another Blog. Powered by Blogger Blogger Templates create by Deluxe Templates. WP by Masterplan