将功能添加到枚举

将功能添加到枚举

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

问题描述



例如:

 枚举模式{
landscape,
portrait,

//梦想...
toString(){console.log这个);
}

或:

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

枚举模式扩展ModeExtension {
landscape,
portrait,
}

当然 toString()函数将包含类似于开关但是用例会沿着以下行:

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

我明白为什么要扩展一个枚举可能是一件奇怪的事情,只是想知道是否可行。

解决方案

在运行时, code> var mode = Mode.portrait; 变量模式是一个数字。你必须覆盖 number.toString 以获得所需的行为 - 这会影响所有数字(和所有枚举) - 这绝对不是你想要的。 / p>

所以这不完全是你以后的,但是这允许你通过在一个单独的类中使用静态方法来封装模式到字符串行为,或者通过使用枚举/模块合并:

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

可以这样使用:

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

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

导出功能解析(mode:string){
return Mode [mode];
}
}

您可以使用这样的一个:

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

我已经包含了一个奖金 parse 也可以这样使用:

  var y = Mode.parse('portrait'); 
console.log(y);


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

for example:

enum Mode {
    landscape,
    portrait,

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

Or:

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

enum Mode extends ModeExtension {
    landscape,
    portrait,
}

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.

解决方案

At runtime, var mode = Mode.portrait; the variable mode is a number. You would have to override number.toString to get the behaviour you want - and that would affect all numbers (and all enums) - which definitely isn't what you want.

So this isn't exactly what you are after, but this allows you to encapsulate the "Mode to string" behaviour by using a static method either in a separate class, or by using an enum/module merge:

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

You can use it like this:

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

Or

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

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

You can use this one like this:

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

And I have included a bonus parse method there as well, which you can use like this:

var y = Mode.parse('portrait');
console.log(y);

Read more on declaration merging (and in particular merging modules with classes, functions, and enums) here.

这篇关于TypeScript:将功能添加到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:35