0

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?

Sandbox.

// 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
}

1 Answer 1

1

If you wish that ctxResolver only modifies props of an object passed as a param:

const ctxResolver = (ctx: Prisma): void => {
  ctx.db = { very_complex_type: 'smth'} // ctxResolver adds db property to ctx
}
    
const getServerSideProps = async (_ctx: Ctx) => {
  ctxResolver(_ctx)

  _ctx // it stays Ctx
}
Sign up to request clarification or add additional context in comments.

4 Comments

better, but i was hoping to not trick typescript :(
That's not a trick. ctxResolver knows exactly only what it should know about ctx - db prop and that's all.
I oversimplified example, but ctxResolver also using data from Req. _ctx can be of two different types. _ctx is not of Ctx type, so it's feels wrong already, a hoped to change it step by step.
It'ok. Just unsimplify it a bit. I can remove my answer at the same time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.