向枚举添加函数 [英] Add functions to an Enum

查看:158
本文介绍了向枚举添加函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在TypeScript中为Enum类型添加函数?

Is it possible to add functions to an Enum type in TypeScript?

例如:

enum Mode {
    landscape,
    portrait,

    // the dream...
    toString() { console.log(this); } 
}

或:

class ModeExtension {
    public toString = () => console.log(this);
}

enum Mode extends ModeExtension {
    landscape,
    portrait,
}

当然, toString()函数将包含类似 switch ,但用例将遵循以下路线:

Of course the toString() function would contain something like a switch But a use-case would flow along the lines of:

class Device {
    constructor(public mode:Mode) {
        console.log(this.mode.toString());
    }
}

我理解为什么要扩展枚举可能很奇怪,只是想知道是否有可能。

I understand why extending an enum might be a strange thing, just wondering if it is possible.

推荐答案

一个与Enum分开的类,并使用它来获取所需的东西,也可以将命名空间合并到Enum中,并在看起来像是在同一地方的地方将其全部获取。

You can either have a class that is separate to the Enum and use it to get things you want, or you can merge a namespace into the Enum and get it all in what looks like the same place.

因此,这并不是您想要的,但是它允许您使用静态方法封装模式到字符串行为。

So this isn't exactly what you are after, but this allows you to encapsulate the "Mode to string" behaviour using a static method.

class ModeUtil {
    public static toString(mode: Mode) {
        return Mode[mode];
    }
}

您可以像这样使用它:

const mode = Mode.portrait;
const x = ModeUtil.toString(mode);
console.log(x);



模式枚举/命名空间合并



您可以将名称空间与枚举合并,以使用其他方法创建看起来像枚举的枚举:

Mode Enum/Namespace Merge

You can merge a namespace with the Enum in order to create what looks like an Enum with additional methods:

enum Mode {
    X,
    Y
}

namespace Mode {
    export function toString(mode: Mode): string {
        return Mode[mode];
    }

    export function parse(mode: string): Mode {
        return Mode[mode];
    }
}

const mode = Mode.X;

const str = Mode.toString(mode);
alert(str);

const m = Mode.parse(str);
alert(m);

这篇关于向枚举添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆