Skip to content

Instantly share code, notes, and snippets.

@drumnickydrum
Created December 30, 2022 21:36
Show Gist options
  • Save drumnickydrum/f71049ea4abd18c5933e7f714ef02891 to your computer and use it in GitHub Desktop.
Save drumnickydrum/f71049ea4abd18c5933e7f714ef02891 to your computer and use it in GitHub Desktop.
[TS: Satisfies Operator] Example of the satisfies operator in TypesScript #typescript
type City = CityName | CityCoordinates;
type CityName = 'New York' | 'Mumbai' | 'Lagos';
type CityCoordinates = {
x: number;
y: number;
};
type User = {
birthCity: City;
currentCity: City;
};
const unsatisfied: User = {
birthCity: 'Mumbai',
currentCity: { x: 6, y: 3 },
};
// No bueno! TS knows birthCity can be type CityCoordinates,
// which does not have the toUpperCase method
unsatisfied.birthCity.toUpperCase();
const satisfied = {
birthCity: 'Mumbai',
currentCity: { x: 6, y: 3 },
} satisfies User;
// Hurray! TS has narrowed this property to type 'Mumbai'
satisfied.birthCity.toUpperCase();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment