typescript destructuring default value code example

Example 1: typescript object destructuring

// declare an interface or a type
interface Person {
  name: string;
  age: string;
}

// destructure name and age from `obj` variable.
const { name, age }: Person = obj;

Example 2: js object destructuring with defaults

// Taken from top stack overflow answer

const { dogName = 'snickers' } = { dogName: undefined }
console.log(dogName) // what will it be? 'snickers'!

const { dogName = 'snickers' } = { dogName: null }
console.log(dogName) // what will it be? null!

const { dogName = 'snickers' } = { dogName: false }
console.log(dogName) // what will it be? false!

const { dogName = 'snickers' } = { dogName: 0 }
console.log(dogName) // what will it be? 0!

Example 3: object destructuring default value

let a, b;

[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7