TypeScript-将值添加到文字类型的数组

时间:2018-08-30 10:54:30

标签: 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的键和值在相同的情况下,我也无法将项目推入数组。

我该如何解决?
谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

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

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';
}
相关问题