gpt4 book ai didi

typescript - 如何从 typescript 中的数组中提取类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:33:09 24 4
gpt4 key购买 nike

有没有办法在 typescript 中声明一个“提取”数组内部类型的类型?

示例:

假设我的代码库中已经有这样的东西:

export interface Cache {
events: Event[],
users: User[]
}
type CacheType = Event[] | User[];

//or maybe:
// type TypeOfProperty = T[keyof T];
// type CacheType = TypeOfProperty<Cache>;

我想要的是等价于此的东西:

type InnerCacheType = Event | User;

但无需每次我向 CacheCacheType 添加内容时手动重新键入它

这在 Typescript 中可能吗?

最佳答案

这在 Typescript 2.8+ 中是可能的。您可以声明 Unpacked<T>输入如下:

type Unpacked<T> = T extends (infer U)[] ? U : T;

现在你可以做

type InnerCacheType = Unpacked<CacheType>; // Event | User

这是 Unpacked 的精简定义documentation 中给出的类型.

关于typescript - 如何从 typescript 中的数组中提取类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com