如何解决如何获取和修改泛型类型中输入类型的名称
type SomethingAggregateData = {
something_aggregate: {
nodes: Something[];
}
}
现在我想制作一个可以帮助我的泛型,看起来像 AggregateData<Something>
所以,我可以像这样使用它:
type AppleAggregateData = AggregateData<Apple>
// will be valid with
type AppleAggregateData = {
apple_aggregate: {
nodes: Apple[];
}
}
我尝试使用 Google,但仍然坚持获取输入类型 Something
名称并使其成为 something_aggregate
键。
解决方法
使用 typescript 4.1+,您可以使用模板文字类型来限制该类型的键名。您只需要提供名称本身。
type AggregateData<T,K extends string> = Record<`${K}_aggregate`,{ nodes: T[] }>;
type Apple = { name: string };
type AppleAggregateData = AggregateData<Apple,'apple'>;
const x: AppleAggregateData = {
apple_aggregate: {
nodes: [{ name: 'macintosh' }],},};
我不确定是否有办法用单个泛型类型参数来表达它,据我所知,没有办法将类型名称作为字符串获取。假设地说,如果我们有这种能力,我们可能会尝试这样做:
// sadly "NameOf<>" does not exist
type AggregateData2<T> = Record<`${Lowercase<NameOf<T>>}_aggregate`,{ nodes: T[] }>;
,
如果所有内部对象都相同(something_aggregate
、apple_aggregate
)但只有节点类型发生变化,您可以将泛型类型传递给SomethingAggregateData
:
type AggregateData<T> = {
aggregate: {
nodes: T[]
}
}
并像这样使用它:
type AppleAggregateData = AggregateData<Apple>
现在类型 AppleAggregateData
应该有类型为 Apple[]
的节点
type AppleAggregateData = {
aggregate: {
nodes: Apple[]
}
}
,
编辑:正如 Jeff 在较新的 Typescript 中提到的,您可以使用字符串文字生成动态键,并避免将完整的 ${resource}_aggregate
作为通用参数传递(如我的示例)
您不能按照您的建议 (something_aggregate
) 在您的类型中定义动态键,但您可以执行以下操作:
type AggregateData<TAggreationKey extends string | number | symbol,TValue> = {
[TKey in TAggreationKey]: {
nodes: TValue[];
}
}
type AppleAggregateData = AggregateData<'apple_aggregate',Apple>;
这会给你你想要的类型,但你需要自己为 { nodes: TValue[] }
写键,它无法计算。
这是一个 typescript playground link,显示了相同的示例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。