TS2536: Type 'xxx' cannot be used to index type 'this'

新手上路,请多包涵

父类的方法修改子类的属性,类型注释怎么写,试了很多写法,还是会报错

class A {
  animate<
    K extends keyof this,
    T extends {
      [key in K]: this[key] extends number ? this[key] : never;
    }
  >(props: Partial<T>) {

    const initialValue: Partial<T> = {}
    const changeValue: Partial<T> = {}

    for (let key in props) {
      changeValue[key] = this[key]
      changeValue[key] = props[key] - (this as any)[key]
    }

    // ...
  }
}

class B extends A {
  width: number
  heigth: number
  name: string
  constructor() {
    super();
    this.heigth = 20
    this.width = 20
    this.name = 'B'
  }
}

const b = new B();

b.animate({
  width: 40,
  heigth: 40
})

Error message:

[tsl] ERROR in /typescript/app/index.ts(16,26)

  TS2536: Type 'Extract<keyof T, string>' cannot be used to index type 'this'.

[tsl] ERROR in /typescript/app/index.ts(17,7)

  TS2322: Type 'number' is not assignable to type 'T[Extract<keyof T, string>] | undefined'.

[tsl] ERROR in /typescript/app/index.ts(17,26)

  TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

阅读 4.7k
1 个回答
class A {
  [s: string]: number | string | ((props: Record<keyof this, number>) => void);

  animate(props: Record<keyof this, number>) {

    const initialValue: Partial<Record<keyof this, number>> = {}
    const changeValue: Partial<Record<keyof this, number>> = {}

    for (let key in props) {
      initialValue[key] = this[key] as number
      changeValue[key] = props[key] - (this[key] as number)
    }
  }
}

class B extends A {
  width: number
  height: number
  name: string

  constructor() {
    super();
    this.height = 20
    this.width = 20
    this.name = 'B'
  }
}

const b = new B();

b.animate({
  width: 40,
  height: 40
})


export default B

因为有个减法,这是最最最没办法的办法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题