ts - 类型收窄

文章目录

    • 问题描述
    • 为什么会出现这个错误?
      • [1. 类型推断机制](#1. 类型推断机制)
      • [2. 函数参数要求具体字面量类型](#2. 函数参数要求具体字面量类型)
      • [3. 类型不匹配](#3. 类型不匹配)
    • 解决方案
      • [方案 1:使用类型断言](#方案 1:使用类型断言)
      • [方案 2:声明 routers 为常量](#方案 2:声明 routers 为常量)
      • [方案 3:显式类型注解](#方案 3:显式类型注解)
      • [方案 4:使用类型提取](#方案 4:使用类型提取)
    • 最佳实践

问题描述

TypeScript 中,我们经常会遇到类似以下的代码和错误。

为什么下面的代码 goRoute(routers.admin) 会报错?

typescript 复制代码
const routers = {
  home: "/",
  admin: "/admin",
  user: "/user"
};

const goRoute = (r: "/" | "/admin" | "/user") => {};

goRoute(routers.admin); // 报错行: 类型"string"的参数不能赋给类型'"/" | "/admin" | "/user"'的参数。

报错如下图:

为什么会出现这个错误?

1. 类型推断机制

TypeScript 会对 routers 具体的字符串字面量类 会将对象字面量的属性类型推断为最宽泛的类型 ,即 string 类型。

所以 routers 的实际类型被推断为:

typescript 复制代码
{
  home: string;
  admin: string;
  user: string;
}

2. 函数参数要求具体字面量类型

goRoute 函数要求参数必须是三个具体的字符串字面量类型之一:'/' | '/admin' | '/user'

3. 类型不匹配

当我们尝试传递 routers.admin(类型为 string)给 goRoute(需要 '/' | '/admin' | '/user')时,TypeScript 会报错,因为 string 比具体的字符串字面量类型更宽泛。

解决方案

方案 1:使用类型断言

typescript 复制代码
goRoute(routers.admin as "/admin");

这种方法简单直接,但不够安全,因为如果 routers.admin 的值后来被修改,类型断言可能会掩盖真正的错误。

方案 2:声明 routers 为常量

typescript 复制代码
const routers = {
  home: "/",
  admin: "/admin",
  user: "/user"
} as const;

as const 是 TypeScript 的常量断言,它会告诉 TypeScript 将所有属性值视为字面量类型,而不是 string 类型。

此时 routers 的类型变为:

typescript 复制代码
{
  readonly home: '/';
  readonly admin: '/admin';
  readonly user: '/user';
}

方案 3:显式类型注解

typescript 复制代码
interface Routes {
  home: "/";
  admin: "/admin";
  user: "/user";
}

const routers: Routes = {
  home: "/",
  admin: "/admin",
  user: "/user"
};

这种方法更显式地定义了类型,适合更复杂的场景。

方案 4:使用类型提取

typescript 复制代码
const routers = {
  home: "/",
  admin: "/admin",
  user: "/user"
};

type RouterValues = (typeof routers)[keyof typeof routers];

const goRoute = (r: RouterValues) => {};

这种方法动态地从 routers 对象中提取所有值的类型作为联合类型。

最佳实践

对于路由配置这种通常不会改变的结构,推荐使用 as const 方案:

typescript 复制代码
const routers = {
  home: "/",
  admin: "/admin",
  user: "/user"
} as const;
const goRoute = (r: "/" | "/admin" | "/user") => {};
goRoute(routers.admin);

这种方式的优点:

  1. 保持代码简洁
  2. 类型安全
  3. 易于维护(添加新路由时类型会自动更新)
  4. 避免硬编码类型

👉点击进入 我的网站

相关推荐
陈广亮3 分钟前
工具指南7-Unix时间戳转换工具
前端
NGBQ121389 分钟前
Adobe-Premiere-Pro-2026-26.0.2.2-m0nkrus 全解析:专业视频编辑软件深度指南
前端·adobe·音视频
北城笑笑10 分钟前
Chrome:Paused in debugger 的踩坑实录:问题排查全过程与终极解决方案( 在调试器中暂停 )
前端·chrome
haorooms13 分钟前
Promise.try () 完全指南
前端·javascript
kyriewen14 分钟前
闭包:那个“赖着不走”的家伙,到底有什么用?
前端·javascript·ecmascript 6
斌味代码17 分钟前
el-popover跳转页面不隐藏,el-popover销毁
前端·javascript·vue.js
该怎么办呢17 分钟前
cesium核心代码学习-01项目目录及其基本作用
前端·3d·源码·webgl·cesium·webgis
踩着两条虫24 分钟前
AI 驱动的 Vue3 应用开发平台 深入探究(十九):CLI与工具链之Create VTJ CLI 参考
前端·ai编程·vite
天下无贼!35 分钟前
【Python】2026版——FastAPI 框架快速搭建后端服务
开发语言·前端·后端·python·aigc·fastapi