【问题标题】:Typescript ignores decorated mobx properties on class type definition打字稿忽略类类型定义上的修饰 mobx 属性
【发布时间】:2021-01-29 06:33:04
【问题描述】:

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

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"
    ]
  }
}

【问题讨论】:

    标签: typescript webpack typescript-typings mobx


    【解决方案1】:

    这里不需要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);
    

    【讨论】:

    • 谢谢!这似乎是问题所在!
    猜你喜欢
    • 2018-01-18
    • 2018-05-16
    • 2020-07-11
    • 2019-01-05
    • 2021-12-16
    • 2018-11-09
    • 2017-03-02
    • 2021-09-07
    • 2014-02-16
    相关资源
    最近更新 更多