【问题标题】:Property does not exist on type (inside of editor)类型上不存在属性(在编辑器内部)
【发布时间】:2018-02-14 15:57:01
【问题描述】:

我有如下TypeScript接口和方法:

namespace a {

  export interface componentType<T extends component> {
    new(element?: HTMLElement): T
    runStaticTick(comp: componentType<T>, tick?: number): void
  }

  export abstract class component {

    public static components: component[] = []

    public findComponent<T extends component>(comp: componentType<T>, callback?: (comp: T) => void) {
      let c = component.components.find(c => c instanceof comp) as T
      c instanceof component && typeof callback == 'function' && callback(c)
      return c
    }

  }

  export abstract class element extends component { }
}

这是 .d.ts

declare namespace a {
  interface componentType<T extends component> {
    new(element?: HTMLElement): T;
  }
  abstract class component {
    findComponent<T extends component>(comp: componentType<T>, callback?: (comp: T) => void): T;
  }
  abstract class element extends component { }
}

然后,为了测试该方法是否有效,我有这个JavaScript:

/// <reference path="../src/test.d.ts"/>

class checklist extends a.element {
  sayHi() { console.log('Hi') }
}

class myclass extends a.component {
  created() {
    this.findComponent(checklist, item => {
      item.sayHi()
    })
  }
}

代码在浏览器中工作,但在编辑器中,它说item 是component 类型,而它应该是checklist 类型。有没有办法解决这个问题,或者这是打字稿的问题?

完整项目:https://github.com/TheColorRed/horsepower

编辑

我找出了导致问题的原因:

export interface componentType<T extends component> {
  new(element?: HTMLElement): T
  runStaticTick(comp: componentType<T>, tick?: number): void
}

如果我注释掉runStaticTick,它会解决智能感知问题。但后来我有错误说它不存在:

错误 TS2339:“componentType”类型上不存在属性“runStaticTick”

【问题讨论】:

  • 我试过了,它可以在 VS Code 中使用。你能发布一个完整的例子吗
  • 这就是我正在使用的,但它不起作用....
  • 可能是我在src 中使用tsconfig.json 文件,在public/app 文件夹中使用jsconfig.json?
  • @TitianCernicova-Dragomir 我创建了一个新项目,并将上面的代码复制到项目中,它在那里工作。为什么它在我当前的项目中不起作用?我试过TS 2.7 和TS 2.8 都不起作用。还有什么可能导致这个问题?
  • @GetOffMyLawn 尝试关闭您的编辑器并重新打开它。有时当我更改 d.ts 文件时,他们内置的 TS 直到我重新打开 VSCode 才会拾取它

标签: javascript typescript visual-studio-code


【解决方案1】:

问题在于方法 runStaticTick 中的属性。

改为使用

comp: componentType<T>

我应该使用

comp: componentType<component>

出于某种原因,T 引起了我不知道的问题。如果有人知道这个问题是什么,请告诉我。

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 2021-09-19
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多