简体   繁体   English

获取嵌套值作为类型

[英]Get nested values as type

Consider following type definition,考虑以下类型定义,

type Parent = {
   children: Child[]
}

type Child = {
   label: string
}

const parent: Parent = {
   children: [
       { label: 'label1' },
       { label: 'label2' }
   ]
}

Now, if I want to generate a genetic type, which contains the label values as key and value as any, is it possible to do it with generics?现在,如果我想生成一个遗传类型,其中包含 label 值作为键和值,是否可以使用 generics 来实现? Do note that I am considering only compile time objects only.请注意,我只考虑编译时对象。

type Labels = {
    label1: any,
    label2: any
}

You can define Child and Parent as generics type, where K extends string is used as generic constraint in order to correctly infer the string literal:您可以将ChildParent定义为 generics 类型,其中K extends string用作通用约束,以便正确推断字符串文字:

type Parent<K extends string> = {
   children: Child<K>[]
}

type Child<K extends string> = {
   label: K
}

type Labels<P extends Parent<any>> = P extends Parent<infer K>
  ? { [Key in K]: string } : never;

Then you can use an helper function in order to automatically infer the label keys from string literals (instead of typing them manually when defining parent as a value):然后,您可以使用帮助程序 function 以便从字符串文字中自动推断 label 键(而不是在将parent定义为值时手动键入它们):

function Parent<K extends string>(parent: Parent<K>) {
  return parent;
}

const p1 = Parent({
   children: [
       { label: 'label1' },
       { label: 'label2' }
   ]
})

Now everything you need is an helper type that using inference and object mapping, transform the keys in the Labels type:现在你需要的只是一个辅助类型,它使用推理和 object 映射,转换Labels类型中的键:

type Labels<P extends Parent<any>> = P extends Parent<infer K>
  ? { [Key in K]: string } : never;

type Labels1 = Labels<typeof p1>;

// Labels1 now is `{ label1: string; label2: string }`

See it in action @ Playground看看它在行动@ 游乐场

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

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