When using the same type (Options<ST extends SwitchType) for useStrategy
options parameter and for toPayload
options, I expected Typescript to infer the correct type for toPayload
options. However, I encountered an error message:
The argument of type 'FirstOptions | SecondOptions' is not assignable to the parameter of type 'FirstOptions'. Property 'b' is missing in type 'SecondOptions' but required in type 'FirstOptions'.(2345)
Is this a limitation of Typescript or am I overlooking something?
enum SwitchType {
First = 'first',
Second = 'second'
}
export type FirstOptions = {
a: string
b: number
}
type SecondOptions = {
a: string
}
export type Options<ST extends SwitchType> = ST extends SwitchType.Second ? SecondOptions : ST extends SwitchType.First ? FirstOptions : never
type Strategy<ST> = ST extends SwitchType.Second ? SecondStrategy : ST extends SwitchType.First ? FirstStrategy : never
type ToPayloadFunction<ST extends SwitchType> = (
options: Options<ST>
) => any
type FirstStrategy = {
toPayload: ToPayloadFunction<SwitchType.First>
}
type SecondStrategy = {
toPayload: ToPayloadFunction<SwitchType.Second>
}
const getStrategy = <ST extends SwitchType>(type: ST): Strategy<ST> => {
const firstStrategy: FirstStrategy = {
toPayload: (options) => {
console.log(options)
}
}
const secondStrategy: SecondStrategy = {
toPayload: (options) => {
console.log(options)
}
}
if(type === SwitchType.Second) return secondStrategy as any
if(type === SwitchType.First) return firstStrategy as any
throw new Error('error')
}
const useStrategy = <ST extends SwitchType>(type: ST, options: Options<ST>): void => {
const { toPayload } = getStrategy(type)
// Argument of type 'FirstOptions | SecondOptions' is not assignable to parameter of type //'FirstOptions'.
// Property 'b' is missing in type 'SecondOptions' but required in type 'FirstOptions'
toPayload(options)
}