I have a node application getServerSideProps function with context object. I need to add new properties or parce data of this object. Is there a way to change typescript object type with minimal use of any and js code change?
// this type cannot be changed
type Complex = { very_complex_type: string}
// this type cannot be changed
type Req = {
headers: Complex
cookies: Complex
}
// this type cannot be changed
type Prisma = {
db: Complex
}
type Ctx = Prisma & Req
// what type should i use for param, return and so on (without any if it can be done)
const ctxResolver = (ctx) => {
ctx.db = { very_complex_type: 'smth'} // ctxResolver adds db property to ctx
}
const getServerSideProps = async (ctx: Req) => {
ctxResolver(ctx)
ctx // how to make it of type Req & Prisma
}
// Attempt 1
const ctxResolver1 = (ctx: Req): ctx is Ctx => {
((ctx as unknown) as Ctx).db = { very_complex_type: 'smth'} // to many type coversions
return true
}
const getServerSideProps1 = (ctx: Req) => {
if (!ctxResolver1(ctx)) return // i don't need if and return here
ctx // ok
}
// Attempt 2
const ctxResolver2 = (ctx: Req): Ctx => {
((ctx as unknown) as Ctx).db = { very_complex_type: 'smth'} // to many type coversions
return ctx as Ctx
}
const getServerSideProps2 = (_ctx: Req) => {
const ctx = ctxResolver2(_ctx) // not sure if _ctx and ctx points to the same object in memory
ctx // ok
}