You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何getCookie参数类型不匹配?TypeScript类型错误排查

问题分析与解决:Cookies-Next类型错误问题

先看你写的代码:

import { getCookie } from 'cookies-next';

export const getAccessTokenFromCookies = (
  req?: NonNullable<Parameters<typeof getCookie>[1]>['req'],
  res?: NonNullable<Parameters<typeof getCookie>[1]>['res'],
): string | undefined => {
  const session = getCookie(sessionKey, { req, res }); // req和res存在类型错误
  if (session) {
    const parsedSession = JSON.parse(session);
    return typeof parsedSession === 'object' && parsedSession != null ? parsedSession[accessTokenKey] : undefined;
  } else return undefined;
};

为什么会出现这个类型错误?

getCookie的第二个参数类型是OptionsType | undefined,而OptionsType是DefaultOptions和AppRouterOptions的联合类型。你单独提取req和res的类型时,TypeScript无法保证这两个参数来自联合类型的同一个分支——比如req可能属于DefaultOptions的类型,res可能属于AppRouterOptions的类型,把它们组合成{req, res}后,这个对象既不符合DefaultOptions的结构,也不符合AppRouterOptions的结构,自然会触发类型不兼容的报错。

怎么解决?

方法一:直接传入完整的options对象(你补充提到的可行方案)

把参数改成接收完整的OptionsType对象,直接传给getCookie,这样TypeScript能明确参数属于联合类型的某一个分支,不会报错:

import { getCookie } from 'cookies-next';

export const getAccessTokenFromCookies = (
  options?: NonNullable<Parameters<typeof getCookie>[1]>
): string | undefined => {
  const session = getCookie(sessionKey, options);
  if (session) {
    const parsedSession = JSON.parse(session);
    return typeof parsedSession === 'object' && parsedSession != null ? parsedSession[accessTokenKey] : undefined;
  } else return undefined;
};

方法二:强制约束req和res来自同一个类型分支

如果一定要分开传req和res,可以用泛型约束两者属于同一个分支:

import { getCookie, DefaultOptions, AppRouterOptions } from 'cookies-next';

type CookieOptions = DefaultOptions | AppRouterOptions;

export const getAccessTokenFromCookies = <T extends CookieOptions>(
  req?: T['req'],
  res?: T['res']
): string | undefined => {
  const session = getCookie(sessionKey, { req, res } as T);
  if (session) {
    const parsedSession = JSON.parse(session);
    return typeof parsedSession === 'object' && parsedSession != null ? parsedSession[accessTokenKey] : undefined;
  } else return undefined;
};

这里用泛型T约束req和res都来自同一个CookieOptions分支,再通过类型断言告诉编译器{req, res}符合T的类型,就能解决报错。

内容的提问来源于stack exchange,提问作者NotX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:52:15