typescript - Nextjs'te NextApiRequest gövdesini nasıl güçlü şekilde tipe bağlarız


API POST Nextjs rotasının gövde tipini tip güvenliğinden yararlanmak için nasıl tanımlayacağımı merak ediyorum? NextApiRequest'te body 'any' olarak tanımlanmış ve NextApiRequest generic değil.

tipi zor olarak kullanmak ama bu tamamen temiz değil

NextJs12 ve typescript 4.4.4 çalıştırıyor

import { NextApiRequest, NextApiResponse } from "next";

interface IBody {
  test: string;
  value: number;
}

const handler = async (
  req: NextApiRequest, <-- whish to have something here like NextApiRequest<TQuery, TBody,..>
  res: NextApiResponse
): Promise<void> => {
  const { body } = req;
  console.log(body as IBody); <--this is not safe at all

  res.status(200).json({ text: "Hello" });
};

export default handler;

Cevap #1

İsteğin gövdesini özel bir tür ile değiştirmek için TypeScript Omit kullanabilirsiniz.

type Override<T1, T2> = Omit<T1, keyof T2> & T2;
    
export type MyCustomRequest = Override<NextApiRequest, { body: MyCustomRequestBody }>
    
export type MyCustomRequestBody = {
  myCustomField: string
}

İlgili makaleler