ahe*_*rve 17 typescript typescript-typings
我经常使用诸如
export type Stuff = 'something' | 'else'
export const AVAILABLE_STUFF: Stuff[] = ['something', 'else']
Run Code Online (Sandbox Code Playgroud)
这样我既可以使用 type Stuff,也可以根据需要迭代所有可用的东西。
这有效,但感觉像是重复了两次信息。而且您必须小心,因为更新Stuff或AVAILABLE_STUFF还需要更新其对应项。
有没有更好的方法来定义数组的类型,或者甚至在某种程度上使用数组来键入一些数据?
Tit*_*mir 13
一个内置选项是使用枚举而不是类型和数组方法。
export enum Stuff {
something = 'something',
else = 'else',
}
export const AVAILABLE_STUFF: Stuff[] = Object.values(Stuff);
Run Code Online (Sandbox Code Playgroud)
另一种选择是从AVAILABLE_STUFF. 为此,我们必须强制编译器推断AVAILABLE_STUFF. 这可以在3.4用as const或之前3.4使用额外的功能。AfterAVAILABLE_STUFF是元组类型,我们可以使用类型查询来获取元素的类型:
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"
Run Code Online (Sandbox Code Playgroud)
对上面代码的一些解释。typeof AVAILABLE_STUFF为我们提供常量 ( ["something", "else"])的类型以获取[number]称为类型查询,并将为我们提供元组中项目的类型。
这(<T extends string[]>(...o: T)=> o)只是我们用来强制编译器推断字符串文字元组类型的 IIFE。它必须是通用的,因为编译器只会在某些情况下推断文字类型和元组(具有约束条件的类型参数string之一)。该as const版本是我建议在可用时使用的版本,因为它更具可读性。
另一种可能性是创建一个对象并使用keyof. 只有当你有任何有用的东西可以存储为值时,我才推荐这种方式(代替null下面的代码)。
const stuffDict = {
something: null,
else: null,
}
type Stuff = keyof typeof stuffDict
const AVAILABLE_STUFF = Object.keys(stuffDict) as Stuff[]
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以这样做-
export const AVAILABLE_STUFF = <const> ['something', 'else'];
export type Stuff = typeof AVAILABLE_STUFF[number];
Run Code Online (Sandbox Code Playgroud)
更多信息 - https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions
| 归档时间: |
|
| 查看次数: |
10363 次 |
| 最近记录: |