I have a custom "Enum" interface that that has a value and a description. I've defined an my enum interface like this-
module App {
export interface IMyEnum {
[index: string]: IMyEnumValue;
}
export interface IMyEnumValue {
value: any;
text: string;
}
}
And my enums like this-
/// <reference path="./enums.interface.ts"/>
module App {
export const StatusEnum: IMyEnum = {
Normal: { value: 100, text: 'Normal' },
Overdue: { value: 200, text: 'Overdue' },
Critical: { value: 300, text: 'Critical' }
}
}
But the typescript compiler is complaining that "Normal" does not exist on type IMyEnum.
let statusCode = StatusEnum.Normal.value;
Is there anyway to do this without defining an IStatusEnum
interface? I think that would be over-engineering.
When you cast StatusEnum
to IMyEnum
, you actually lose type info, leaving you only with an indexer: [index: string]: IMyEnumValue
Option 1: use strings
let statusCode = StatusEnum["Normal"].value;
You'll lose compile-time safety on enum names (eg StatusEnum["normal"].value
will give a runtime error).
Option 2: get rid of IMyEnum
and let the compiler infer the type.
export const StatusEnum = {
Normal: { value: 100, text: 'Normal' },
Overdue: { value: 200, text: 'Overdue' },
Critical: { value: 300, text: 'Critical' }
}
let statusCode = StatusEnum.Normal.value;
That way you'll have type safety and autocompletion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.