next.js api NextApiRequest接口重新声明

flmtquvp  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(259)

我想将NextApiRequest.body定义为泛型。

下一个.d.ts

import type { NextApiRequest as _NextApiRequest } from 'next';

declare module 'next' {
  interface NextApiRequest<T = any> extends _NextApiRequest {
    body: T;
    foot: T; // for test
  }
}

/页面/api/您好.ts

import type { NextApiRequest } from 'next';

export default async function handler(req: NextApiRequest<boolean>, res:any){
  // when I hover the mouse below codes, then I see these.
  console.log(req.body); // (property) NextApiRequest<boolean>.body: any
  console.log(req.foot); // (property) NextApiRequest<boolean>.foot: boolean
}

如何重新声明NextApiRequest接口?

cbeh67ev

cbeh67ev1#

我找到了一个解决办法。

下一个.d.ts

import type { NextApiRequest } from 'next';

declare module 'next' {
  interface TypedNextApiRequest<T = any> extends NextApiRequest {
    body: T;
    foot: T; // for test
  }
}

我声明了TypedNextApiRequest而不是NExtApiRequest,并使用它。

相关问题