Skip to content

Instantly share code, notes, and snippets.

@rileyhilliard
Last active April 12, 2019 21:39
Show Gist options
  • Save rileyhilliard/e3612f26d35df0f93142015f82c4bb2f to your computer and use it in GitHub Desktop.
Save rileyhilliard/e3612f26d35df0f93142015f82c4bb2f to your computer and use it in GitHub Desktop.
Array Destructure
// a 'Person' object requires 'first' and 'last'
// properties whose values are strings
interface Person {
first: string;
last: string;
}
// This defines that the first functional argument
// must be an Array of 'Person' objects, then destructs
// the first person's first and last name properties
const helloFirstPerson = ([{ first, last }]: Person[]) =>
`Hello ${first} ${last}!`;
const people = [
{ first: 'John', last: 'Doe' },
{ first: 'Jane', last: 'Smith' }
];
// outputs "Hello John Doe!"
helloFirstPerson(people);
/* --------- Example of a Type Error ----------- */
// This creates an array argument that will be invalid for
// the helloFirstPerson() function, because there are no 'last'
// props on the 'people' objects
const badArgs = [{ first: 'John' }, { first: 'Jane' } ];
// Type Error!
// Property 'last' is missing in type '{ first: string; }'
helloFirstPerson(badArgs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment