-
Notifications
You must be signed in to change notification settings - Fork 0
How `satisfies` works
Daisho Komiyama edited this page Feb 22, 2024
·
6 revisions
type WithId = {
id: string
}
interface ColorWithId extends WithId {
color?: string
}
// Declaring myColor1 with ColorWithId interface
const myColor1:ColorWithId = { id: 'a', color: 'red' }
myColor1.color.substring(0, 1)
// ^ TypeError: 'myColor1.color' is possibly 'undefined'.
// To fix this, we need to apply optional chaining: `myColor1.color?.substring(0, 1)`
// But this doesn't make sense because it's obvious that there is a color property with the value 'red'!
// How about using `as`?
const myColor2 = { id: 'a', color: 'red' } as ColorWithId
myColor2.color.substring(0, 1)
// ^ TypeError: 'myColor1.color' is possibly 'undefined'.
// The same as above. You need the optional chaining.
// ***** How about using `satisfies`? ******
const myColor3 = { id: 'a', color: 'red' } satisfies ColorWithId
myColor3.color.substring(0, 1) // no TypeError! Because the value "satisfies" the type.
// Does `satisfies` still check the type correctly??
const myColor4 = { id: 'a', colors: 'red' } satisfies ColorWithId
// ^ TypeError: 'colors' does not exist in type 'ColorWithId'
// Yes, it does.