我需要创建一个对象,该对象将包含一个名为“state”的属性,该属性将具有通用类型,所有其他属性将是具有覆盖上下文的函数。我不确定这是否可能,因此我决定写在这里。
我有一个代码:
declare interface ContextModule<State> {
state: State
}
export declare interface SuperModule<State = any> {
state?: State | any,
[methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
}
const lol = {
getFoo (): any {
return this.state.foo
}
} as SuperModule
在这段代码中我没有任何错误。它执行成功,但如果我添加
declare interface ContextModule<State> {
state: State
}
export declare interface SuperModule<State = any> {
state?: State | any,
[methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
}
const lol = {
getFoo (): any {
return this.state.foo
},
+ state: { // added this property
+ foo: 'string'
+ }
} as SuperModule
然后我会看到输出
Conversion of type '{ getFoo(this: ContextModule<any>): any; state: { foo: string; }; }' to type 'SuperModule<any>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Property 'state' is incompatible with index signature.
Type '{ foo: string; }' is not comparable to type '(this: ContextModule<any>, ...args: any[]) => any'.
Type '{ foo: string; }' provides no match for the signature '(this: ContextModule<any>, ...args: any[]): any'.ts(2352)
我了解该问题与尝试转换属性的 TypeScript 有关state
to [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
,但是为什么如果我在声明动态属性之前声明这个属性
可能有人看到了同样的问题。希望得到您的帮助,谢谢!