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

如何在TypeScript解构Next.js useRouter的query时指定id为string类型

在Next.js中指定路由查询参数id为string类型

你可以根据实际场景选择以下几种方式处理:

1. 类型断言(快速实现,需确保参数合法性)

如果能确定路由中一定存在id且为单个字符串,可以在解构时直接用类型断言指定类型:

import { useRouter } from 'next/router';

// 方式1:解构后断言
const { query: { id } } = useRouter();
const stringId = id as string;

// 方式2:解构时直接重命名并断言
const {
  query: { id: stringId }
} = useRouter();
// 此时stringId的类型为string

注意:若实际路由中id不存在(undefined)或为数组(比如重复参数?id=1&id=2),这种方式会引发运行时错误,需谨慎使用。

2. 结合类型守卫(安全可靠)

通过类型守卫检查id的实际类型,确认是string后再传入目标函数,避免运行时异常:

import { useRouter } from 'next/router';

const { query: { id } } = useRouter();

if (typeof id === 'string') {
  // TypeScript会自动推断此处id为string类型
  yourTargetFunction(id);
} else {
  // 处理id不合法的情况,比如跳转错误页、提示用户参数异常等
  console.error('id参数不合法,请检查路由');
}

3. 扩展Next.js路由类型(适用于固定路由规则)

如果你的路由配置明确id是必传的单个字符串参数,可以扩展NextRouter的类型,让TypeScript默认识别query.id为string:

// 在项目的types/next.d.ts文件中添加类型扩展
import type { NextRouter } from 'next/router';

declare module 'next/router' {
  interface NextRouter {
    query: {
      id: string;
    };
  }
}

之后在组件中解构时,id的类型会自动被识别为string:

const { query: { id } } = useRouter();
// id的类型为string

注意:这种方式仅适用于该路由固定存在id参数的场景,否则会与实际运行时情况冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:15:34