简体   繁体   English

如何从 Typescript 中的 object 值数组生成类型

[英]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.

相关问题 Typescript-从数组生成TS对象 - Typescript - generate TS object from array Typescript - 从联合或数组派生对象类型 - Typescript - derive object type from union or array 如果键值已经存在,如何从数组中删除对象 - 打字稿 - How to remove object from an array if key value already exists - typescript 如何从 typescript 中的 object 数组创建或过滤具有已定义键和值的 object 数组 - How to create or filter an object array with defined key and value from an object array in typescript 从 Typescript 中的 object 生成接口 - Generate Interface from an object in Typescript 如何从其他 arrays 生成基于数组索引的交集,无论是数组还是 object 类型? - How does one generate an array-index based intersection, either of array or object type, from other arrays? 如何从 TypeScript 中的对象数组中获取类型 - How to get the type from array of objects in TypeScript 如何在打字稿中为对象的通用键类型分配值类型? - How assign a value type to a generic key type of an object in typescript? 如何从java中的Array Class类型对象中检索值? - How to retrieve value from Array Class type object in java? 在 Typescript 中,如何在存储然后从数组访问所述对象时维护对象类型? - In Typescript, how do I maintain an objects type when storing and then accessing said object from an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM