以下代码可用于在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
};
当前回答
export enum PaymentType {
Cash = 1,
Credit = 2
}
var paymentType = PaymentType[PaymentType.Cash];
其他回答
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。
@basarat的回答很棒。下面是一个你可以使用的简化但有点扩展的例子:
export type TMyEnumType = 'value1'|'value2';
export class MyEnumType {
static VALUE1: TMyEnumType = 'value1';
static VALUE2: TMyEnumType = 'value2';
}
console.log(MyEnumType.VALUE1); // 'value1'
const variable = MyEnumType.VALUE2; // it has the string value 'value2'
switch (variable) {
case MyEnumType.VALUE1:
// code...
case MyEnumType.VALUE2:
// code...
}
我认为你应该试试这个,在这种情况下,变量的值不会改变,它的工作方式很像枚举,使用类也可以,唯一的缺点是你可以错误地改变静态变量的值这是我们不希望在枚举中发生的。
namespace portal {
export namespace storageNames {
export const appRegistration = 'appRegistration';
export const accessToken = 'access_token';
}
}
使用typescript@next中提供的自定义转换器(https://github.com/Microsoft/TypeScript/pull/13940),您可以从字符串字面类型创建字符串值的枚举对象。
请查看我的npm包,ts-transformer-enumerate。
使用示例:
// The signature of `enumerate` here is `function enumerate<T extends string>(): { [K in T]: K };`
import { enumerate } from 'ts-transformer-enumerate';
type Colors = 'green' | 'yellow' | 'red';
const Colors = enumerate<Colors>();
console.log(Colors.green); // 'green'
console.log(Colors.yellow); // 'yellow'
console.log(Colors.red); // 'red'
一个俗套的说法是:-
CallStatus.ts
enum Status
{
PENDING_SCHEDULING,
SCHEDULED,
CANCELLED,
COMPLETED,
IN_PROGRESS,
FAILED,
POSTPONED
}
export = Status
Utils.ts
static getEnumString(enum:any, key:any):string
{
return enum[enum[key]];
}
如何使用
Utils.getEnumString(Status, Status.COMPLETED); // = "COMPLETED"