以下代码可用于在TypeScript中创建enum:
enum e {
hello = 1,
world = 2
};
这些值可以通过以下方式访问:
e.hello;
e.world;
我如何创建一个字符串值enum ?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
以下代码可用于在TypeScript中创建enum:
enum e {
hello = 1,
world = 2
};
这些值可以通过以下方式访问:
e.hello;
e.world;
我如何创建一个字符串值enum ?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
当前回答
我也有同样的问题,然后想出了一个很好用的函数:
每个条目的键和值都是字符串,并且相同。 每个条目的值都是从键派生出来的。(即。“不要重复你自己”,不像字符串值的常规枚举) TypeScript类型成熟且正确。(防止拼写错误) 还有一种简单的方法可以让TS自动完成您的选项。(如。打字MyEnum。,并立即看到可用的选项) 还有其他一些优点。(见答案底部)
效用函数:
export function createStringEnum<T extends {[key: string]: 1}>(keysObj: T) {
const optionsObj = {} as {
[K in keyof T]: keyof T
// alternative; gives narrower type for MyEnum.XXX
//[K in keyof T]: K
};
const keys = Object.keys(keysObj) as Array<keyof T>;
const values = keys; // could also check for string value-overrides on keysObj
for (const key of keys) {
optionsObj[key] = key;
}
return [optionsObj, values] as const;
}
用法:
// if the "Fruit_values" var isn't useful to you, just omit it
export const [Fruit, Fruit_values] = createStringEnum({
apple: 1,
pear: 1,
});
export type Fruit = keyof typeof Fruit; // "apple" | "pear"
//export type Fruit = typeof Fruit_values[number]; // alternative
// correct usage (with correct types)
let fruit1 = Fruit.apple; // fruit1 == "apple"
fruit1 = Fruit.pear; // assigning a new fruit also works
let fruit2 = Fruit_values[0]; // fruit2 == "apple"
// incorrect usage (should error)
let fruit3 = Fruit.tire; // errors
let fruit4: Fruit = "mirror"; // errors
现在有人可能会问,这个“基于字符串的enum”比只使用:
type Fruit = "apple" | "pear";
有几个优点:
Auto-complete is a bit nicer (imo). For example, if you type let fruit = Fruit., Typescript will immediately list the exact set of options available. With string literals, you need to define your type explicitly, eg. let fruit: Fruit = , and then press ctrl+space afterward. (and even that results in unrelated autocomplete options being shown below the valid ones) The TSDoc metadata/description for an option is carried over to the MyEnum.XXX fields! This is useful for providing additional information about the different options. For example: You can access the list of options at runtime (eg. Fruit_values, or manually with Object.values(Fruit)). With the type Fruit = ... approach, there is no built-in way to do this, which cuts off a number of use-cases. (for example, I use the runtime values for constructing json-schemas)
其他回答
打印稿0.9.0.1
enum e{
hello = 1,
somestr = 'world'
};
alert(e[1] + ' ' + e.somestr);
打印稿操场
这对我来说很管用:
class MyClass {
static MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
or
module MyModule {
export var MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
8)
更新:在发布这篇文章后不久,我发现了另一种方法,但忘记发布更新(然而,上面已经有人提到过了):
enum MyEnum {
value1 = <any>"value1 ",
value2 = <any>"value2 ",
value3 = <any>"value3 "
}
TypeScript 2 + 4。
你现在可以直接将字符串值分配给enum成员:
enum Season {
Winter = "winter",
Spring = "spring",
Summer = "summer",
Fall = "fall"
}
更多信息见#15486。
打印稿1.8 +
在TypeScript 1.8+中,你可以创建一个字符串文字类型来定义类型,并为值列表创建一个同名的对象。它模仿字符串enum的预期行为。
这里有一个例子:
type MyStringEnum = "member1" | "member2";
const MyStringEnum = {
Member1: "member1" as MyStringEnum,
Member2: "member2" as MyStringEnum
};
它将像字符串enum一样工作:
// implicit typing example
let myVariable = MyStringEnum.Member1; // ok
myVariable = "member2"; // ok
myVariable = "some other value"; // error, desired
// explict typing example
let myExplicitlyTypedVariable: MyStringEnum;
myExplicitlyTypedVariable = MyStringEnum.Member1; // ok
myExplicitlyTypedVariable = "member2"; // ok
myExplicitlyTypedVariable = "some other value"; // error, desired
确保输入对象中的所有字符串!如果不这样做,那么在上面的第一个例子中,变量将不会隐式地类型化为MyStringEnum。
非常非常简单的Enum string (TypeScript 2.4)
import * from '../mylib'
export enum MESSAGES {
ERROR_CHART_UNKNOWN,
ERROR_2
}
export class Messages {
public static get(id : MESSAGES){
let message = ""
switch (id) {
case MESSAGES.ERROR_CHART_UNKNOWN :
message = "The chart does not exist."
break;
case MESSAGES.ERROR_2 :
message = "example."
break;
}
return message
}
}
function log(messageName:MESSAGES){
console.log(Messages.get(messageName))
}
如果你想要的主要是易于调试(相当类型检查),不需要为枚举指定特殊值,这是我正在做的:
export type Enum = { [index: number]: string } & { [key: string]: number } | Object;
/**
* inplace update
* */
export function enum_only_string<E extends Enum>(e: E) {
Object.keys(e)
.filter(i => Number.isFinite(+i))
.forEach(i => {
const s = e[i];
e[s] = s;
delete e[i];
});
}
enum AuthType {
phone, email, sms, password
}
enum_only_string(AuthType);
如果您希望支持遗留代码/数据存储,则可以保留数字键。
这样,您就可以避免键入两次值。