Created
December 30, 2022 21:36
-
-
Save drumnickydrum/f71049ea4abd18c5933e7f714ef02891 to your computer and use it in GitHub Desktop.
[TS: Satisfies Operator] Example of the satisfies operator in TypesScript #typescript
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
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