将函数添加到 Enum [英] Add functions to an Enum

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

问题描述

是否可以在 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());
    }
}

我明白为什么扩展 enum 可能是一件奇怪的事情,只是想知道它是否可能.

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);

模式枚举/命名空间合并

您可以将命名空间与 Enum 合并,以创建具有其他方法的 Enum:

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);

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

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