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

问题描述

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

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

在其他地方,我正在导入此类以用作类型定义,并在访问这些预期属性时收到错误

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看起来像下面的

{
  "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意味着您需要类构造函数,而不是类实例。但是据我了解,实际上您有许多类实例。

typeof可用于以下情况:

class Foo {
  // some code here
}

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


const newInstanceOfFoo = createClass(Foo);