我正在尝试为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): error TS2322: Type 'Actions' is not assignable to type 'MessageActions'.
Property 'newMessage' is missing in type 'Actions'.
src/app/App.ts(35,34): error TS2345: Argument of type 'typeof MessageStore' is not assignable to parameter of type 'Store'.
Property 'register' is missing in type 'typeof MessageStore'.'.
这是公平的,因为我知道我应该使用接口,但后来我不能在我的代码中扩展类。 这是repo的链接,以防您想要尝试
有人能帮助我吗?我觉得我错过了一些明显的东西
答案 0 :(得分:2)
正如在IRC上讨论的那样,createStore(store:Store)意味着createStore采用Store(或其子类型)类型的实例,而不是类型&#39; sa商店的子类型。对于后者,您希望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;
后者允许您返回传入的相同类型,而不是总是返回操作,如果需要的话。
createStore()
需要做同样的事情另外
this.register(messageActions.newMessage, this.handleNewMessage);
会导致问题,因为在handleNewMessage中将不定义this
。 this.handleNewMessage返回一个函数,而不是像其他语言一样返回绑定的委托。您要么需要this.handleNewMessage.bind(this)
要么message => this.handleNewMessage(message)
- 后一种形式要求您明确写出所有参数,而前一种形式不会,但如果要注册的参数的签名,则会丢失类型检查错误handleNewMessage曾经不同意。
答案 1 :(得分:0)
子类的Typescript定义作为参数
这不是错误。您发布的代码很好:
declare class Actions {
}
declare class Flummox {
createActions(key: string, store: Actions): Actions;
}
class MessageActions extends Actions {
newMessage(content: string) {
return content;
}
}
class Flux extends Flummox {
constructor() {
super();
this.createActions('messages', MessageActions);
}
}
如果需要父类,则允许将子类作为参数传递。