【发布时间】:2018-10-08 18:22:54
【问题描述】:
我有一个这样的对象:
const routes = {
home: { path: '/', page: 'home' },
profile: { path: '/profile', page: 'users/profile' }
}
我想从中定义一个派生类型,如下所示:
type RouteName = keyof typeof routes,创建类似"home" | "profile"的类型。
但是,我不能这样做:
for (let name in routes) {
router.add({ name, ...routes[name]})
}
因为编译器抱怨 routes[name] 是隐式类型 any:
Element implicitly has an 'any' type because type '{ home: { path: string; page: string; }; profile: { path: string; page: string; };' has no index signature.
如果我将路由的定义修改为:
interface RouteDefinition {
path: string
page: string
}
const routes: {[key: string]: RouteDefinition} = {
home: { path: '/', page: 'home' },
profile: { path: '/profile', page: 'users/profile' }
}
生成的类型type RouteName = keyof typeof routes 现在是string 而不是"home"|"profile"。
我当然可以定义一个硬编码的RouteName 类型,但如果不清楚,我会尽量避免在两个地方定义路由名称,尤其是当对象的键严格定义一组可能性。
对象只需要定义一次,永远不需要重新分配。我尝试了Readonly<>、casting 等的一系列组合,但无法弄清楚。有没有办法做到这一点?
(我使用的是 Typescript 2.8.1)
【问题讨论】:
-
使用
for/in时,推断类型有this issue。但看起来他们并不打算改变当前的行为。
标签: typescript types mapped-types