如何从打字稿中的数组中提取类型? [英] How do I extract a type from an array in typescript?

查看:30
本文介绍了如何从打字稿中的数组中提取类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在打字稿中声明一个提取"数组内部类型的类型?

Is there a way to declare a type in typescript that 'extracts' the inner type of an array?

示例:

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

Let's say I already have something like this in my codebase:

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

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

我想要的是相当于这个的东西:

What I want is something which would be equivalent to this:

type InnerCacheType = Event | User;

但是每次我向 CacheCacheType

这在 Typescript 中可行吗?

Is this possible in Typescript?

推荐答案

这在 Typescript 2.8+ 中是可能的.您可以按如下方式声明 Unpacked 类型:

This is possible with Typescript 2.8+. You can declare an Unpacked<T> type as follows:

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

现在可以了

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

这是 文档.

This is a condensed definition of the Unpacked type given in the documentation.

这篇关于如何从打字稿中的数组中提取类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆