TS(2352)声明具有动态属性的对象和一个具有特定类型的属性

谢尔盖·沃尔科夫(Sergey Volkov)

我需要创建一个对象,该对象将包含一个名称为“ 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关联的问题[methodName: string]: (this: ContextModule<State>, ...args: any[]) => any,但为什么在动态属性声明之前声明此属性

可能有人看到了同样的问题。希望对您有所帮助,谢谢!

消费者

我可以使它正常工作的唯一方法是使用交集类型,但是似乎只能使用创建动态类型和具有固定属性(类型与动态道具不同)的交集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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何创建一个具有未知数量的字符串属性和一个具有数字类型的特定属性的接口?

是否有一个表示具有任何属性但没有数组的对象的类型

Joi验证对象数组,以便只有一个对象具有特定属性

返回具有特定属性和类型的对象

JSDoc是一个对象,所有属性(无论名称如何)都具有相同的类型

具有有效属性名称列表中只有一个属性的对象的类型

如果对象具有特定属性,则仅使用它们创建一个新对象

基于另一个值的具有多个对象类型的可编码解码属性

我如何简洁地断言一个对象具有特定的属性?

findOneAndUpdate-更新数组中具有特定属性的第一个对象

具有范围属性和一个额外的数字

一个接口中具有不同方法和属性的不同对象

如何声明 TS 类型,该类型是具有类型为数字或字符串值的属性的对象数组?

具有包含特定类型的对象属性的TypeScript类型

如何在jQuery中共有两个具有一个特定属性的对象的值求和?

从另一个对象构造一个动态对象,该对象具有带有不同键值对的 dictionary<string, object> 属性

如何声明3个彼此具有属性的对象

获取具有父级一个属性的特定类的所有属性

如何为具有动态属性的扩展对象创建类型

如何通过DI注入两个相同类型但具有一个属性不同的对象?

解析和映射具有动态属性的 JSON 对象

约束类型以具有特定类型的属性

将具有一个属性的对象转换为父属性

将对象属性(包括具有私有设置器的属性)深度复制到另一个相同类型的对象

Javascript 对象有一个具有两个值的属性

如何从具有多个属性的类中获取一个特定的属性

在python中解析XML:假设子节点具有特定属性,则选择一个属性

具有动态属性的类型定义

显示一个复杂的c#对象,该对象在WPF中具有属性和内部集合