[英]How to generate a type from an array of object value in Typescript
I am having an array of routes as such:我有一系列这样的路线:
export const routes = [
{ name: 'Home', component: HomeScreen },
{ name: 'CreateProgram', component: CreateProgramScreen },
{ name: 'AddExercises', component: AddExercisesScreen },
]
I'd like to generate the kind of type alias as below programmatically from the name of the route:我想从路线的名称以编程方式生成如下类型的别名:
type RouteNames = 'Home' | 'CreateProgram' | 'AddExercises'
Type the array as const
so it doesn't get automatically widened, and then you can use [number]
on its type to get a union of all object types, and then access ["name"]
to get to type of the name
property.将数组键入
as const
使其不会自动加宽,然后您可以在其类型上使用[number]
来获取所有 object 类型的并集,然后访问["name"]
以获取name
属性的类型.
export const routes = [
{ name: 'Home', component: HomeScreen },
{ name: 'CreateProgram', component: CreateProgramScreen },
{ name: 'AddExercises', component: AddExercisesScreen },
] as const;
type RouteNames = (typeof routes)[number]["name"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.