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

TypeScript中RouteRecordName无includes属性问题求助

问题解决:Property 'includes' does not exist on type 'RouteRecordName'

问题根源

你遇到的报错和ES版本配置无关,核心原因是RouteRecordName的类型定义为string | symbol | undefined——其中symbol类型并没有includes方法,TypeScript因此抛出编译错误。

可行解决方案

方法1:用类型守卫过滤非字符串类型

通过typeof判断确保处理的是字符串,同时覆盖undefined和symbol的情况:

import { useRoute } from 'vue-router'
import { computed } from 'vue'

const route = useRoute()
const isRead = computed(() => {
  if (typeof route.name !== 'string') {
    return true // 根据你的业务逻辑返回默认值
  }
  return !(route.name.includes('create') || route.name.includes('edit'))
})

方法2:类型断言(适用于路由name全为字符串的场景)

如果你的项目路由配置中,所有name都是字符串(不会使用symbol),可以直接断言类型:

import { useRoute } from 'vue-router'
import { computed } from 'vue'

const route = useRoute()
const isRead = computed(() => {
  return !( (route.name as string).includes('create') || (route.name as string).includes('edit') )
})

注:原代码中的xxx ? false : true可以简化为!xxx,逻辑等价且更简洁。

方法3:兼容symbol类型的处理(如果路由name可能为symbol)

如果存在用symbol作为路由name的场景,可以先将其转为字符串再判断:

import { useRoute } from 'vue-router'
import { computed } from 'vue'

const route = useRoute()
const isRead = computed(() => {
  const nameStr = String(route.name)
  return !(nameStr.includes('create') || nameStr.includes('edit'))
})

注意:symbol转为字符串后格式为Symbol(xxx),只有当symbol的描述中包含create/edit时才会匹配,需结合业务需求调整。

总结

这不属于TypeScript的问题,是类型不匹配导致的编译报错,不需要更换includes方法,只需针对RouteRecordName的类型做对应处理即可。

内容的提问来源于stack exchange,提问作者Kauê Zuquetto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:18:28