【问题标题】:Typescript type defined by array由数组定义的打字稿类型
【发布时间】:2019-02-10 21:49:47
【问题描述】:

我正在使用 keyof、typeof、... 枚举和数组是否可以有一个“数据源”?

例如:
- 我想要一个枚举类型
- 和一个数组

但我想定义一个事实来源。目前我定义了 'limited','low','medium','high' 3 次,我有很多这样的“数据类”

const myArray: string[] = [
    'limited',
    'low',
    'medium',
    'high'
];
type MyStringEnumType =
    'limited'
    | 'low'
    | 'medium'
    | 'high';

enum MyEnum
{
    Limited = 'limited',
    Low = 'low',
    Medium = 'medium',
    High = 'high'
}

type Both = MyStringEnumType | MyEnum;

let testVar1: Both = MyEnum.Limited; // works
let testVar2: Both = 'limited'; // works
console.log(myArray[0], myArray.length); // works

谢谢!

问候 疯狂x13

【问题讨论】:

  • 为什么不使用普通枚举?
  • TypeScript String Union to String Array的可能副本(或相关)
  • 我称之为副本。 TypeScript String Union to String Array 的可能重复项
  • 上面的代码好像是对的,有什么问题或者问题吗?
  • @RezaRahmati:这是因为我有很多这样的类和一些数据,我想要“一个真实的来源”,而不是双重定义数据集。谢谢!

标签: arrays typescript types


【解决方案1】:

好的,感谢 smnbbrv 我找到了一个“好的”版本(没有“MyStringEnumType”)

  • 现在我有一个枚举
  • 还有一个数组
export class ComplexityOptions
{
    public static get Values()
    {
        return Object.keys(ComplexityOptions.Option).map((key: any) => (ComplexityOptions.Option[key]));
    }
}

export module ComplexityOptions
{
    export enum Option
    {
        Limited = 'limited',
        Low = 'low',
        Medium = 'medium',
        High = 'high'
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2017-02-20
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2019-06-15
    • 2023-02-05
    • 2018-01-16
    • 2020-07-07
    相关资源
    最近更新 更多