I’m trying to implement a middleware for Koa that slightly extends type of state on context, but the extended state doesn’t cast successfully to the base state if I try to cast function that uses extended state to a function that uses base state. I’ve spent 3 hours already figuring out what is wrong, but I still don’t understand.
I’ve made the smallest reproducible sample:
type A = {
foo: number
}
type B = A & {
bar: number
}
type FuncA = (middie: A) => void
type FuncB = (middie: B) => void
const fa = {} as FuncA
const fb = {} as FuncB
const fc: FuncA = fb // doesn't work
So the last row complains that bar
doesn’t exist on A
, but I’m trying to cast extended version of A
to A
(base version), which should logically be fine since all props on A exist on B. But for some reason TS made it wise versa which is not what I expect.
Casting B to A itself, without a function, works correctly, so I think there is something to do with how TS works with function arguments?
Playground: click