gpt4 book ai didi

javascript - 子类的 typescript 定义作为参数

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:30 27 4
gpt4 key购买 nike

我正在尝试为 flummox 编写类型定义但我不完全明白我应该怎么写。要点是我们应该继承 Store、Actions 和 Flummox 类并将它们传递给函数。
下面是带有操作的代码示例:

import { Flummox, Actions, Store } from 'flummox';
class MessageActions extends Actions {
newMessage(content: string) {
return content;
}
}
class MessageStore extends Store {
constructor(flux: Flummox) {
super();

const messageActions: MessageActions = flux.getActions('messages'); // error here
this.register(messageActions.newMessage, this.handleNewMessage);
}
}

class Flux extends Flummox {
constructor() {
super();

this.createActions('messages', MessageActions);
this.createStore('messages', MessageStore, this); //error here
}
}

以及我开始的定义:

/// <reference path="eventemitter3.d.ts"/>

declare module "flummox" {

type ActionId = string;

class Store {
register(action: ActionId | Function, handler: Function): void;
}

class Actions {

}

class Flummox extends EventEmitter3.EventEmitter.EventEmitter3 {
createActions(key: string, actions: Actions, constructorArgs?: any | any[]): Actions;
getActions(key: string): Actions;
removeActions(key: string): Actions;

createStore(key: string, store: Store, constructorArgs?: any | any[]): Store;
getStore(key: string): Store;
removeStore(key: string): Store;
}
}

我收到以下错误:

src/app/App.ts(16,11):错误 TS2322:类型“Actions”不可分配给类型“MessageActions”。
“操作”类型中缺少属性“newMessage”。
src/app/App.ts(35,34):错误 TS2345:“typeof MessageStore”类型的参数不可分配给“Store”类型的参数。
“typeof MessageStore”类型中缺少属性“register”。

这很公平,因为我知道我可能应该使用接口(interface),但那样我将无法在我的代码中扩展类。这是 repo 的链接如果你想尝试一下

有人能帮帮我吗?我觉得我错过了一些明显的东西

最佳答案

正如在 IRC 上讨论的那样,createStore(store: Store) 意味着 createStore 采用类型 Store(或其子类型)的实例,而不是 Store 的子类型类型 .对于后者,您希望 store 的类型包含返回 Store 或 Store 的子类型的构造签名。所以

createActions(key: string, actions: Actions, constructorArgs?: any | any[]): Actions;

应该是

createActions(key: string, actions: { new(...args: any[]): Actions }, constructorArgs?: any | any[]): Actions;

createActions<T extends Actions>(key: string, actions: { new(...args: any[]): T }, constructorArgs?: any | any[]): T;

如果需要,后者允许您返回传入的相同类型,而不是总是返回 Actions。

createStore() 也需要做同样的事情


还有

this.register(messageActions.newMessage, this.handleNewMessage);

会导致问题,因为 this 在 handleNewMessage 中未定义。 this.handleNewMessage 返回一个函数,而不是像其他语言那样的绑定(bind)委托(delegate)。您要么想要 this.handleNewMessage.bind(this) 要么想要 message => this.handleNewMessage(message) - 后一种形式要求您显式写出所有参数,而如果要注册的参数和 handleNewMessage 的签名不一致,前一种形式不会丢失类型检查错误。

关于javascript - 子类的 typescript 定义作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30504002/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com