diff --git a/README.md b/README.md index 05b9151..9432720 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1108 TILs and counting..._ +_1109 TILs and counting..._ --- @@ -1008,6 +1008,7 @@ _1108 TILs and counting..._ - [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md) - [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md) - [Re-Export An Imported Type](typescript/re-export-an-imported-type.md) +- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md) - [Zero-Config Environments For Trying Out Types](typescript/zero-config-environments-for-trying-out-types.md) ### Unix diff --git a/typescript/type-narrowing-with-similarly-shaped-objects.md b/typescript/type-narrowing-with-similarly-shaped-objects.md new file mode 100644 index 0000000..b0c8303 --- /dev/null +++ b/typescript/type-narrowing-with-similarly-shaped-objects.md @@ -0,0 +1,46 @@ +# Type Narrowing With Similarly Shaped Objects + +Let's say we have a type with several properties and a variable of that type. + +```typescript +type User = { + firstName: string + lastName: string + age: number + email: string +} + +const liz: User = { + firstName: 'Liz', + lastName: 'Lemon', + age: 38, + email: 'liz@example.com' +} +``` + +We can use variables of this type in _narrower_ contexts as long as the +properties that are present have aligning types. + +For instance, we can pass a `User` to this `sendNewsletter` function. Even +though the types don't match exactly, the type of `sendNewsletter`'s parameter +is a subset of `User`. + +```typescript +const sendNewsletter = ({ + firstName, + email, +}: { + firstName: string; + email: string; +}) => { + console.log(`Sending newsletter to ${firstName} at ${email}`); +}; + +sendNewsletter(liz); +// "Sending newsletter to Liz at liz@example.com" +``` + +This is a form of [_type +narrowing_](https://www.typescriptlang.org/docs/handbook/2/narrowing.html) +through [structural +subtyping](https://www.typescriptlang.org/docs/handbook/type-compatibility.html).