Skip to content

Latest commit

 

History

History
46 lines (38 loc) · 1.07 KB

type-narrowing-with-similarly-shaped-objects.md

File metadata and controls

46 lines (38 loc) · 1.07 KB

Type Narrowing With Similarly Shaped Objects

Let's say we have a type with several properties and a variable of that type.

type User = {
  firstName: string
  lastName: string
  age: number
  email: string
}

const liz: User = {
  firstName: 'Liz',
  lastName: 'Lemon',
  age: 38,
  email: '[email protected]'
}

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.

const sendNewsletter = ({
  firstName,
  email,
}: {
  firstName: string;
  email: string;
}) => {
  console.log(`Sending newsletter to ${firstName} at ${email}`);
};

sendNewsletter(liz);
// "Sending newsletter to Liz at [email protected]"

This is a form of type narrowing through structural subtyping.