是否可以从数组创建打字稿类型? [英] Is it possible to create a typescript type from an array?

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

问题描述

我经常使用诸如

export type Stuff = 'something' | 'else'
export const AVAILABLE_STUFF: Stuff[] = ['something', 'else']

这样我既可以使用 Stuff 类型,也可以根据需要迭代所有可用的东西.

This way I can both use the type Stuff, and iterate over all the available stuffs if need be.

这行得通,但感觉像是重复了两次信息.而且您必须小心,因为 StuffAVAILABLE_STUFF 的更新也需要相应的更新.

This works, but it feels like repeating twice the information. And you have to be careful because an update of either Stuff or AVAILABLE_STUFF also requires an update of its counterpart.

有没有更好的方法来定义数组的类型,或者甚至在某种程度上使用数组来键入一些数据?

Is there a better way to define the type from the Array, or even to somewhat use the array to type some data ?

推荐答案

一个内置选项是使用枚举而不是类型和数组方法.

One built-in option would be to use an enum instead of the type and array approach.

export enum Stuff {
    something = 'something',
    else = 'else',
}

export const AVAILABLE_STUFF: Stuff[] = Object.values(Stuff);

另一种选择是从 AVAILABLE_STUFF 的类型中提取类型.为此,我们必须强制编译器为 AVAILABLE_STUFF 推断字符串文字元组.这可以在 3.4 中使用 as const 或在 3.4 之前使用额外的函数来完成.在 AVAILABLE_STUFF 是元组类型之后,我们可以使用类型查询来获取元素的类型:

Another option is to extract the type from the type of AVAILABLE_STUFF. To do this we must force the compiler to infer a tuple of string literals for AVAILABLE_STUFF. This can be done in 3.4 with as const or before 3.4 using an extra function. After AVAILABLE_STUFF is a tuple type we can just use a type query to get the type of the elements:

export const AVAILABLE_STUFF = (<T extends string[]>(...o: T)=> o)('something', 'else'); // typed as ["something", "else"]
// export const AVAILABLE_STUFF = ['something', 'else'] as const; // typed as ["something", "else"]  in 3.4
export type Stuff = typeof AVAILABLE_STUFF[number] //"something" | "else"

对上面代码的一些解释.typeof AVAILABLE_STUFF 给了我们常量的类型 (["something", "else"]) 来获得 [number] 被称为类型查询 并会给我们一个项目的类型在元组中.

A few explanations of the above code. typeof AVAILABLE_STUFF gives us the type of the constant (["something", "else"]) to get the [number] is called a type query and will give us the type of an item in the tuple.

((...o: T)=> o) 只是我们用来强制编译器推断字符串文字元组的 IIFE类型.它必须是通用的,因为编译器只会在某些情况下推断文字类型和元组(具有 string 约束的类型参数就是其中之一).as const 版本是我推荐使用的版本,因为它更具可读性.

The (<T extends string[]>(...o: T)=> o) is just an IIFE we use to force the compiler to infer a string literal tuple type. It has to be generic as the compiler will only infer literal types and tuples in certain cases (a type parameter with a constraint of string being one of them). The as const version is what I would recommend using when it becomes available as it is more readable.

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

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