首页 > 解决方案 > 获取嵌套值作为类型

问题描述

考虑以下类型定义,

type Parent = {
   children: Child[]
}

type Child = {
   label: string
}

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

现在,如果我想生成一个基因类型,其中包含标签值作为键和任何值,是否可以使用泛型来做到这一点?请注意,我只考虑编译时对象。

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

标签: typescripttypescript-generics

解决方案


您可以将Childand 定义Parent为泛型类型,其中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;

然后,您可以使用辅助函数从字符串文字中自动推断标签键(而不是在定义parent为值时手动键入它们):

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

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

现在你需要的只是一个辅助类型,它使用推理和对象映射,转换类型中的键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 }`

看看它在行动@游乐场


推荐阅读