微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。