【问题标题】:How to let VSCode/Typescript to do auto complete on imported classes?如何让 VSCode/Typescript 对导入的类进行自动完成?
【发布时间】:2020-07-29 09:31:46
【问题描述】:

假设我有一个文件,class.ts

//I tried implementing interface, but it won't help, with or without the interface
interface FooInterface {
    bar: Function
}

class Foo implements FooInterface {

    bar() {
        console.log('Hello world!');
    }

}

export = new Foo();

在我的另一个文件 index.js 中,我希望 VS Code 能够读取 Foo 类中的内容并自动完成,但事实并非如此。

const Foo = require('./class');

///Expecting the .bar() suggestion after typing Foo., but it didn't happen
Foo.bar();

我错过了什么吗?我应该怎么做才能让 VS Code 识别类中可用的方法/属性?很多第三方库都可以做到这一点。

【问题讨论】:

    标签: typescript class visual-studio-code import export


    【解决方案1】:

    这个模式对我来说有点奇怪,所以我为你创建了一个沙盒,

    希望对你有帮助

    这里是沙盒:https://codesandbox.io/s/vigorous-fog-hngl5?file=/src/index.js:0-72

    如果您想查看差异,我也会在此处粘贴代码

    interface FooInterface {
      bar: () => void
    }
    
    export default class Foo implements FooInterface {
    
      bar() {
          console.log('Hello world!');
      }
    
    }
    

    这是你如何导入它的:

    import Foo from './class';
    
    const FooInstance = new Foo();
    

    这是结果:

    【讨论】:

    • 完美运行。太感谢了。你能解释一下import { Foo } from './class'import Foo from ./class`之间的区别吗?前者不行,换成后者就行了。
    • 如果您通过 default 关键字(例如 export default Foo)导出模块,您将像这样导入它:import Foo from './class',如果您只使用 export 而没有像这样的默认关键字:export Foo 您需要像这样导入它import { Foo } from './class'@user3622260 阅读:javascript.info/import-export
    猜你喜欢
    • 2021-04-30
    • 2020-11-07
    • 2021-07-10
    • 2014-08-21
    • 2019-01-24
    • 2021-06-05
    • 2021-02-12
    • 2020-05-07
    • 2020-09-11
    相关资源
    最近更新 更多