Coming from the world of mobile development, I am currently delving into Angular for a new project.
I find it quite convenient to add fields to an enum in languages like Swift or Kotlin. For instance, in Swift:
enum Status: Int {
case connected = 0, disconnected = 1
var title: String {
switch self {
case .connected:
return "Connected"
case .disconnected:
return "Disconnected"
}
}
var color: UIColor {
switch self {
case .connected:
return .green
case .disconnected:
return .red
}
}
}
Usage example:
let status = Status.connected
print(status.title) // Output Connected
print(status.color) // Output green
In TypeScript, when attempting to achieve similar functionality, I found two potential methods: Pipe and namespace.
My implementation using the pipe method:
export enum Status {
connected = 0, disconnected = 1
}
@Pipe({name: 'color'})
export class StatusColor implements PipeTransform {
transform(value: Status): string {
switch (value) {
case Status.connected:
return 'green';
case Status.disconnected:
return 'red';
}
}
}
@Pipe({name: 'title'})
export class StatusTitle implements PipeTransform {
transform(value: Status): string {
switch (value) {
case Status.connected:
return 'Connected';
case Status.disconnected:
return 'Disconnected';
}
}
}
Implementation in HTML:
user.status | color
user.status | title
While this approach provides a visually appealing code in the HTML usage, the drawback is having to create a custom pipe for each field and declare it in the app.module. With numerous enums, it can result in redundant code and declarations. Is this still considered good practice?
My alternate solution using the namespace method:
export enum Status {
connected = 0, disconnected = 1
}
export namespace Status {
export function titleOf(state: Status): string {
switch (state) {
case Status.disconnected:
return 'Disconnected';
case Status.connected:
return 'Connected';
}
}
export function colorOf(state: State): string {
switch (state) {
case Status.disconnected:
return 'red';
case Status.connected:
return 'green';
}
}
}
Usage in HTML:
Status.titleOf(user.status)
Status.colorOf(user.status)
This second approach is more straightforward but lacks the elegance of the first method.
So, what would be the recommended approach for achieving this requirement? Is there a better way to streamline the code by creating a single pipe with sub-names for each transformation?