Real world example I ran into
With this foundational knowledge thanks to the great Steve Sewell, one scenario which I ran into issues that were solved by satisfies
is as follows:
type ModeA = {
mode: 'A'
data: DataA[]
}
type ModeB = {
mode: 'B'
data: DataB[]
}
type State = (ModeA | ModeB) & {
// Some common types.
}
const defaultState: State = {
mode: 'A'
data: []
}
const MyComponent = () => {
const [state, dispatch] = useReducer(reducer, defaultState)
// ?^ type-error: 'A' | 'B' not assignable to 'B'
}
With defaultState: State
and data not having any values, typescript cannot infer. So we need to instead use satisfies.
const defaultState = {
mode: 'A'
data: []
} satisfies State
The as
keyword, would not work here to fix the issue either since in this context as
doesn’t tell typescript which data is being used DataA
or DataB
so it can’t tell us if its right or wrong.