更新的问题:
在客户端应用程序中,我正在实现一个事件处理系统,类似于 Redux 的工作方式。
我将事件类型定义为自定义 Event
类的子类。所有此类子类都有自己的 type
静态属性。
我通过创建子类的实例并将其发送到主处理函数来触发事件。
在此主处理程序中,我想使用 type
来决定调用哪个特定处理程序。
由于事件是 Event 子类的实例,因此我使用 event.constructor.type
。
它编译并工作正常,但 IDE 提示:类型“Function”上不存在属性“type”
(我也在代码示例中标记了它)。
我应该忽略该消息,还是有更好的方法从实例访问该静态属性?
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”),编辑器提示:“Function”类型上不存在属性“type”。
我在 Intellij Idea 和 Typescript Playground (www.typescriptlang.org/play) 中尝试过。我应该忽略编辑器消息,还是有更好的方法从实例访问该静态属性?
最佳答案
您可以为 BaseClass
构造函数创建类型:
interface BaseClassStatic {
type: string;
new (): BaseClass;
}
然后转换到它:
function getNumber(x: BaseClass): number {
return map[(x.constructor as BaseClassStatic).type];
}
关于typescript - 从实例获取类(静态)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633015/