typescript 如何把字面量数组转为联合类型声明?

作者站长头像
站长
· 阅读数 12

如果这个字面量数组没有指定类型的话是可以的:

const routes = [
  { path: '/test' }
] as const

type paths = typeof routes[number]['path']

但是如果routes指定了类型(为了书写的时候有语法提示),就不行,paths会推断成string类型:

const routes: RouteRecordRaw[] = [
  { path: '/test' }
] as const

type paths = typeof routes[number]['path']

有什么解决方法吗

解决方法

import type { RouteRecordRaw } from 'vue-router'

type Route<T> = Omit<RouteRecordRaw, 'path'> & { path: T }

function defineRoutes<T extends string>(routes: Route<T>[]) {
  return routes
}

const routes = defineRoutes([
  {
    path: '/contract/index'
  }
])

type paths = typeof routes[number]['path']
回复
1个回答
avatar
test
2024-06-19

改成泛型,用个函数包一下

interface RouteRecordRaw<T extends string> {
  path: T
}

function defineRoutes<T extends string>(routes: RouteRecordRaw<T>[]) {
  return routes
}

const routes = defineRoutes([
  { path: '/test' },
  { path: '/foo' },
])

type paths = typeof routes[number]['path']
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容