TypeScriptで戻り値が一致する条件式
ifとelseは予約語なので、thenとunlessで
code:ts
type TIF = <T>(
condition: boolean,
funcs: {
then: () => T extends void ? never : T
unless: () => T extends void ? never : T
}
) => T
const tif: TIF = (condition, { then, unless }) => {
return condition ? then() : unless()
}
// こう使う
const x = tif(true, {
then: () => {
return 'hey'
},
unless: () => {
return 0 // error: Type '() => number' is not assignable to type '() => string'.
},
})
#TypeScript