首页 > 解决方案 > TypeScript - 将值添加到文字类型的数组

问题描述

我正在尝试完成类似以下的操作...我为数组中的允许值定义了一个类型,但是当我尝试向数组添加值时,出现错误。
这是类型定义:

export const SupportedFieldRules = {
    REQUIRED: 'required',
    NUMBER: 'number',
    BOOLEAN: 'boolean'
};

export type ValidationRule = keyof typeof SupportedFieldRules;

export class FieldModel {
    rules: ValidationRule[] = [];
}

在这里我想如何使用它:

const model = new FieldModel();
model.rules.push(SupportedFieldRules.REQUIRED);

我收到错误:

Type 'string' is not assignable to type '"REQUIRED"'.

据我了解,我在这里有两个问题......其中一个是键SupportedFieldRules是大写的,值是小写的,我需要找出如何从键的SupportedFieldRules不是键创建类型(我不想要依赖于键,仅依赖于值)。 第二个问题,即使 SupportedFieldRules 的键和值在相同的情况下,我也无法将项目推送到数组中。

我该如何解决?
谢谢!

标签: typescript

解决方案


对于第一个问题,您需要:

export type ValidationRule = (typeof SupportedFieldRules)[keyof typeof SupportedFieldRules];

对于第二个问题,您需要避免将可变对象属性从字符串文字默认“扩大”到字符串。一种方法是通过一个标识函数运行对象,该函数推断string每个属性受约束的类型(与此答案相比):

function asLiterals<T extends string, U extends {[k: string]: T}>(obj: U): U { return obj; }
export const SupportedFieldRules = asLiterals({
    REQUIRED: 'required',
    NUMBER: 'number',
    BOOLEAN: 'boolean'
});

另一种方法是使用命名空间而不是对象:

export namespace SupportedFieldRules { 
  export const REQUIRED = 'required';
  export const NUMBER = 'number';
  export const BOOLEAN = 'boolean';
}

推荐阅读