我试图为氟莫克斯编写一个类型定义,但我不完全理解我应该如何编写它。要点是,我们应该对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'.'.
这是公平的,因为我知道我可能应该使用接口,但这样我就无法扩展代码中的类。这里有一个指向存储库的链接,以防您想要尝试它
有人能帮我吗?我觉得我错过了一些显而易见的东西
发布于 2015-05-29 20:58:50
正如在IRC上讨论的那样,createStore( Store : Store)意味着createStore接受一个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);将导致问题,因为this将在handleNewMessage中未定义。this.handleNewMessage返回一个函数,而不是像其他语言那样的绑定委托。您要么希望this.handleNewMessage.bind(this)或message => this.handleNewMessage(message) -后者要求您显式地写出所有参数,而前者则不会丢失类型错误,如果要注册的参数的签名和handleNewMessage的签名不一致的话。
发布于 2015-05-28 10:42:26
作为参数的子类的类型记录定义
这不是这里的错误。您发布的代码很好:
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);
}
}试试看
如果需要父类,则允许将子类作为参数传递。
https://stackoverflow.com/questions/30504002
复制相似问题