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