In the angular project I am currently working on, we are utilizing typescript for development.
One key aspect of our project is an enum that defines various statuses:
export enum Status {
ACTIVE = 'ACTIVE',
DEACTIVE = 'DEACTIVE'
}
The duplication of properties/fields within the enum serves a specific purpose related to serialization and deserialization. Without it, Status.ACTIVE
would be represented as 0
in terms of ordinality.
For visualization purposes, we require a mapping of these status labels to more user-friendly words; for example, translating 'ACTIVE' to 'Active'.
To achieve this, we have implemented namespaces in the following way:
export namespace Status {
export function displayName(s: Status){
const mapping = {Status.ACTIVE: 'Active', ...};
return mapping[s];
}
}
This approach simplifies the usage of Status
, allowing for both direct access to enums like Status.ACTIVE
and using Status.displayName(s)
. This keeps the code organized within the same 'classname' concept defined in the status.ts file.
However, given that default linting rules suggest avoiding namespaces with messages like 'namespace' and 'module' are disallowed (no-namespace), some questions arise:
- Does the use of namespaces introduce any performance or optimization concerns?
- Is there a more efficient way to achieve the same functionality while maintaining the 'class' name consistency?
- Could exporting another function without a namespace within the same file serve as a viable solution? Although this may not fully meet the original requirement of having the same class name.
An alternative implementation could look like the following:
status.ts
export Status {
ACTIVE = 'ACTIVE'
}
export function statusToDisplayName(s: Status){
const map = {...};
return map[s];
}
usage.ts
import {Status, statusToDisplayName} from 'some/path/status';
...
status = Status.ACTIVE;
statusToDisplay = statusToDisplayName(status);