Last active
April 12, 2019 21:39
-
-
Save rileyhilliard/e3612f26d35df0f93142015f82c4bb2f to your computer and use it in GitHub Desktop.
Array Destructure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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