Typescript 忽略 class 类型定义上的装饰 mobx 属性

Typescript ignores decorated mobx properties on class type definition

这是一个简化的例子。我有一个 class 定义,使用的装饰器如下:

export default class AnimationController {
  @observable animationTime: number = 0;
  @computed({keepAlive: true}) get interpolatedJoints(){}
  @computed({keepAlive: true}) get currentAnimation(){}
}

我在其他地方导入此 class 以用作类型定义并在访问这些预期属性时出现错误。

import AnimationController from './AnimationController';

type Animate = {
  controllers: typeof AnimationController[];
};

//...

        if(
          (this.controllers[0].currentAnimation.name === 'slice' || this.controllers[0].currentAnimation.name === 'punch')
          && this.controllers[0].interpolatedJoints.currentAnimationInfo.lowerKeyframeNumber > 1
          && this.controllers[0].interpolatedJoints.currentAnimationInfo.lowerKeyframeNumber < 4
        ){

这会在 .currentAnimation.interpolatedJoints 上引发错误:

Property 'currentAnimation' does not exist on type 'typeof AnimationController'. [2339] [2 times]

Property 'interpolatedJoints' does not exist on type 'typeof AnimationController'. [2339]

我正在使用以下版本的 webpack:

    "ts-loader": "^8.0.4",
    "typescript": "^4.0.3",
    "webpack": "^4.44.2",

我的 tsconfig.json 看起来像下面9ing

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2019",
      "dom"
    ]
  }
}

这里不需要typeof:

type Animate = {
  controllers: typeof AnimationController[];

  // Should be:
  controllers: AnimationController[];
};

typeof AnimationController 表示您需要 class 构造函数,而不是 class 实例。但据我所知,你实际上有 class 个实例数组。

typeof 可以在这样的情况下使用:

class Foo {
  // some code here
}

function createClass(klass: typeof Foo) {
  return new klass();
}


const newInstanceOfFoo = createClass(Foo);