如果这个字面量数组没有指定类型的话是可以的:
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']
改成泛型,用个函数包一下