#Cannot narrow Class' generic type in assertion function (extending Koa Context)

2 messages · Page 1 of 1 (latest)

fluid shore
#

I'm trying to properly type a function (addRender) which adds a property to an object (which is typed as a Generic object with an index signature {[key: PropertyKey]: any})
So flow control downstream from that function is able to realize the type has been narrowed for that specific key.

This is for use with Koa's app.context, though I re-created the types involved in a minimal self-contained example to show my issue

It could be that 1. I can do this in a different way 2. This would need a change to the DefinitelyTyped/koa definitions 3. This isn't possible with TypeScript
I would be happy with advice in any direction :)

open crescentBOT
#
f0x52#0

Preview:```ts
...
function addRender<C>(
app: Application<C>
): asserts app is Application<C & RenderContext> {
;(
app as Application<C & RenderContext>
).context.render = (view: string) => {
console.log("rendering", view)
}
}

addRender(app)

app.use(ctx => {
// @ts-expect-error Should error with: An argument for 'view' was not provided. but instead render is typed 'any', so no error
ctx.render()
})```