繁体   English   中英

TypeScript 迭代 object 并从值创建一个类型

[英]TypeScript Iterate over object and create a type from the values

鉴于我有这样的 object:

const props = [
    { name: 'car', list: { brand: 'audi', model: 's4' }
    { name: 'motorcycle', list: { type: 'ktm', color: 'orange' }
] as constant;

我想创建一个代表这样的类型:

type Props = {
    car?: 'brand' | 'model',
    motorcycle?: 'type' | 'color'
};

我得到的最接近的是这样的:

type Props = Partial<Record<typeof props[number]['name'], typeof props[number]['list']>

但返回如下内容:

type Props = {
    car?: { brand: 'audi', model: 's4' } | { type: 'ktm' | color: 'orange' } | undefined,
    motorcycle?: { brand: 'audi', model: 's4' } | { type: 'ktm' | color: 'orange' } | undefined
}

我怎样才能达到预期的效果?

您可以使用 TypeScript 4.1 ( docs ) 中引入的密钥重新映射来实现此目的:

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;
// }

请注意,就像使用Partial时一样,可选属性类型会获得额外但无害的| undefined | undefined

TypeScript操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM