Javascript TypeScript迭代对象并根据值创建类型
假设我有一个这样的物体:Javascript TypeScript迭代对象并根据值创建类型,javascript,typescript,types,typescript-typings,Javascript,Typescript,Types,Typescript Typings,假设我有一个这样的物体: const props=[ {名称:'car',列表:{品牌:'audi',车型:'s4'} {名称:'motorcycle',列表:{类型:'ktm',颜色:'orange'} ]作为常数; 我想创建一个表示如下内容的类型: 类型道具={ 汽车?:“品牌”|“车型”, 摩托车?:“类型”|“颜色” }; 我得到的最接近的结果是这样的: type Props=Partial您可以使用TypeScript 4.1()中引入的键重新映射来实现这一点: type Inde
const props=[
{名称:'car',列表:{品牌:'audi',车型:'s4'}
{名称:'motorcycle',列表:{类型:'ktm',颜色:'orange'}
]作为常数;
我想创建一个表示如下内容的类型:
类型道具={
汽车?:“品牌”|“车型”,
摩托车?:“类型”|“颜色”
};
我得到的最接近的结果是这样的:
type Props=Partial您可以使用TypeScript 4.1()中引入的键重新映射来实现这一点:
type IndexKeys<T> = Exclude<keyof T, keyof []>
type ListProp = { name: string, list: object }
type GetName<P> = P extends ListProp ? P['name'] : never
type GetListKeys<P> = P extends ListProp ? keyof P['list'] : never
type PropsFromList<PropList extends ReadonlyArray<ListProp>> = {
[i in IndexKeys<PropList> as GetName<PropList[i]>]?: GetListKeys<PropList[i]>
}
type Props = PropsFromList<typeof props>
// Inferred type:
// Props: {
// car?: "brand" | "model" | undefined;
// motorcycle?: "type" | "color" | undefined;
// }
类型索引键=排除
类型ListProp={name:string,list:object}
键入GetName=P扩展ListProp?P['name']:从不
键入GetListKeys
=P扩展ListProp?keyof P['list']:从不
类型PropsFromList={
[i在索引键中作为GetName]?:GetListKeys
}
类型Props=PropsFromList
//推断类型:
//道具:{
//汽车?:“品牌”|“型号”|未定义;
//摩托车?:“类型”|“颜色”|未定义;
// }
请注意,与使用Partial
时一样,可选属性类型会得到额外但无害的| undefined
很高兴能帮上忙!第二件事似乎是可能的,但为了澄清这个问题,我建议为它创建一个新问题。已经知道了!\o你就是那个人……泰