从实例

时间:2017-03-06 18:32:27

标签: typescript

更新了问题:

在客户端应用程序中,我正在实现一个事件处理系统,类似于Redux的工作方式 我将事件类型定义为自定义Event类的子类。所有这些子类都有自己的type静态属性 我通过创建子类的实例并将其发送到主处理函数来触发事件。 在这个主处理程序中,我想使用type来决定调用哪个特定的处理程序。

由于事件是Event子类的实例,因此我使用event.constructor.type 它编译并正常工作,但IDE抱怨:Property 'type' does not exist on type 'Function'(我在代码示例中也标记了它)。

我应该忽略该消息,还是有更好的方法从实例访问该静态属性?

type State = {};

class Event {
    public static type: string;
}

class MouseMoveEvent extends Event {
    public static type = "MouseMoveEvent";
    constructor(public x: number, public y: number) {
        super();
    }
}

class KeypressEvent extends Event {
    public static type = "KeyPressEvent";
    constructor(public key: string) {
        super();
    }
}

function handleMouseMove(event: MouseMoveEvent, state: State): State {
    // return some new state
}

function handleKeyPress(event: KeyPressEvent, state: State): State {
    // return some new state
}

const handlerMap: { [type: string]: (event: Event, state: State) => State; } = {
    [MouseMoveEvent.type]: (event: Event, state: State) => handleMouseMove(event as MouseMoveEvent, state),
    [KeyPressEvent.type]: (event: Event, state: State) => handleKeyPress(event as KeyPressEvent, state)
    // etc.
};

// The main handler, it receives all triggered events, and decides which specific handler to call, based on the `type` property.
function handleEvent(event: Event, state: State): State {
    // the editor complains here
    return handlerMap[event.constructor.type](event, state);
}


原始问题:

class BaseClass {
    public static type: string;
}

class SubClass1 extends BaseClass {
    public static type = "SubClass1";
}

class SubClass2 extends BaseClass {
    public static type = "SubClass2";
}

const map: {[type: string]: number} = {
    [SubClass1.type]: 1,
    [SubClass2.type]: 2
};

function getNumber(x: BaseClass): number {
    return map[x.constructor.type]; // complains here
}

const foo = new SubClass1();
console.log(getNumber(foo));

当这段代码编译并运行时(控制台输出“SubClass1”),编辑器会抱怨:“函数”类型中不存在属性“类型”。

我在Intellij Idea和Typescript游乐场(www.typescriptlang.org/play)中尝试过。我应该忽略编辑器消息,还是有更好的方法从实例访问该静态属性?

1 个答案:

答案 0 :(得分:2)

您可以为BaseClass构造函数创建一个类型:

interface BaseClassStatic {
    type: string;
    new (): BaseClass;
}

然后投向它:

function getNumber(x: BaseClass): number {
    return map[(x.constructor as BaseClassStatic).type];
}