Skip to content

Instantly share code, notes, and snippets.

@MichaelDimmitt
Last active August 28, 2023 15:19
Show Gist options
  • Save MichaelDimmitt/01ef4ab3880181c95b2b042af1db903d to your computer and use it in GitHub Desktop.
Save MichaelDimmitt/01ef4ab3880181c95b2b042af1db903d to your computer and use it in GitHub Desktop.

Adding this to the doc that I give learning javascript, just posting here too for visibility

So you are a new dev on the team and want to learn object de-structuring ?

const defaultTypes = {
  foo: 'hi',
  bar: 'hi',
  baz: 'extra'
}
const gaz = 'bye'
const { baz, gaz: moo, ...best } = { ...defaultTypes, gaz }
console.log({ best })
// { "best": { "foo":"hi", "bar":"hi"} }

^ says it all

renames ...rest to ...best but under the hood it is still rest (also I know this is no the best code 😰)
de-structures gaz out of the object and renames it to moo.
adds gaz to the object using spread operator
removes properties from an object while retaining everything else.
baz and gaz are not included in best

More fun ones

const defaultTypes = {
  foo: 'hi',
  bar: 'hi',
  baz: 'extra'
}

const newTypes  = {
  foo: 'bye',
  bar: 'bye'
}

console.log( { ...defaultTypes, ...newTypes } )
// {
//  foo: 'bye',
//  bar: 'bye',
//  baz: 'extra'
//}

^ updates the values that match keeps items from default types that do not match.

how to typescript an object destructure

const { baz, ...best }: { foo: string, bar: string, baz: string, gaz: string }
  = { ...defaultTypes, gaz }

so you give the type to the actual object that is being returned
we could rewrite as

const actualObject: { foo: string, bar: string, baz: string, gaz: string }
  = { ...defaultTypes, gaz }

Final note: de-structuring objects is key based
de-structuring arrays is index based

Mow lets talk about the weakMaps data structure ... jk!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment