TS(2352) 声明具有动态属性的对象和具有特定类型的一个属性 [英] TS(2352) Declare object with dynamic properties and one property with specific type
问题描述
我需要创建一个对象,该对象将包含一个名为state"的属性,该属性将具有泛型类型,而所有其他属性将是具有覆盖上下文的函数.我不确定这是否可能,因此我决定写信到这里.
I need to create object which will contain one property with name 'state' which will have generic type and all other properties will be functions with overriden context. I'm not sure that it is possible, because of this I decided to write to here.
我有一个代码:
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
在这段代码中,我没有任何错误.它执行成功,但如果我会添加
In this code I don't have any errors. It executes successfully, but if I will add
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
转换为 [methodName: string]: (this: ContextModule<State>, ...args: any[])=>任何
,但是为什么我在声明动态属性之前声明了这个属性
I understand that problem linked with that TypeScript trying to cast property state
to [methodName: string]: (this: ContextModule<State>, ...args: any[]) => any
, but why if I declared this property before declaration for dynamic properties
可能有人看到了同样的问题.希望得到您的帮助,谢谢!
May be somebody saw the same problem. Hope on your help, thanks!
推荐答案
我能让它干净利落地工作的唯一方法是使用交集类型,但似乎动态类型和具有固定属性的类型的交集(不同的类型到动态道具)只能使用 Object.assign
创建.
The only way I could get this to work cleanly is using an intersection type, but it appears that the intersection of dynamic types and types with fixed properties (of differing type to the dynamic props) can only be created using Object.assign
.
这是我的简化示例:
interface MyType {
requiredProp1: string
}
interface MyOtherType{
[key: string]: number
}
type ISect = MyType & MyOtherType
const obj: ISect = Object.assign({ requiredProp1: "ff" }, { foo: 1 })
const rp1 = obj.requiredProp1 //string
const foo = obj.foo //number
这篇关于TS(2352) 声明具有动态属性的对象和具有特定类型的一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!