【问题标题】:Typescript: How can I define a type from an string array?Typescript:如何从字符串数组中定义类型?
【发布时间】:2020-12-11 13:03:42
【问题描述】:

目前我这样做:

export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'];
export type IEbookType = 'epub' | 'mobi' | 'pdf' | 'azw3' | 'txt' | 'rtf';

拥有一组有效的书籍类型和一个定义它们的打字稿类型。这看起来很多余。

有没有办法使用数组来定义类型? 我的目标显然是避免两次写书的类型。因此,也欢迎任何其他解决方案。

【问题讨论】:

  • 可以使用CValidEbookTypes[number],但是需要在数组后面加上as const才能将类型推断为字面量。

标签: javascript arrays typescript types


【解决方案1】:

通过使用as const,typescript 将字符串文字推断为CValidEbookTypes 的类型。然后你可以使用typeof CValidEbookTypes[number]:

export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'] as const;
export type IEbookType = typeof CValidEbookTypes[number];
// IEbookType will be "epub" | "mobi" | "pdf" | "azw3" | "txt" | "rtf"

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 2019-01-02
    • 2023-03-21
    • 2019-10-09
    • 2016-07-17
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2018-03-01
    相关资源
    最近更新 更多