微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获取和修改泛型类型中输入类型的名称

如何解决如何获取和修改泛型类型中输入类型的名称

我有一个重复的任务,就是在这个形状中创建新类型:

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_aggregateapple_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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?