Typescript未正确推断扩展类型

uqdfh47h  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(201)

我正在尝试使NextApiRequestbody对打字脚本更友好。我有以下代码。

// this is an upstream type from a library I've included here
export interface NextApiRequest {
    query: Partial<{
        [key: string]: string | string[];
    }>;
    cookies: Partial<{
        [key: string]: string;
    }>;
    body: any;
}

export type BaseSageRequest = { query?: any, method: 'GET' | 'POST' | 'DELETE' | 'PATCH' | 'PUT', body?: any };
export type SageApiRequest<T extends BaseSageRequest> = NextApiRequest & {
    query: T["query"] | NextApiRequest["query"];
    method: T["method"] | NextApiRequest["method"];
    body:   T['body'] | NextApiRequest["body"];
}

export default async function createChat(
  req: SageApiRequest<{body: {lol: string}, method: 'POST'}>
) {
  // req.body is of type any, not of type {lol: string}
}

然而,当我试图从createChat函数中访问req.body时,我看到req.body的类型是any,而不是我期望的{lol: string}类型。
我肯定声明了我的BaseSageRequest类型不正确,但我不知道如何修复它,使body采用T的而不是BaseSageRequest
如何设置类似于上面的类型脚本类型,使req.body采用传递给SageApiRequest的类型?我想强制传递给SageApiRequest的任何类型必须包含method,并且可以包含bodyquery

sy5wg1nm

sy5wg1nm1#

在与类型系统进行了相当多的斗争之后,我发现了一些有用的东西:

export interface BaseSageRequest extends NextApiRequest {
  method: "GET" | "POST" | "DELETE" | "PATCH" | "PUT";
}

export interface SageApiRequest<TBody = any, TQuery extends Partial<NextApiRequest['query']> = Partial<NextApiRequest['query']>> extends BaseSageRequest {
  query: TQuery;
  body: TBody;
}

相关问题