18

我正在使用 SailsJS 开发后端服务器。它基本上将所有模型助手服务以及我自己的服务注入到全局命名空间中。如果我能够为这些服务获得 Intellisense,我将受益匪浅。

我首先为 lodash 和 node 设置了类型并安装了全局类型定义。创建jsconfig.jsontsconfig.json文件后,它就像一个魅力。

接下来,我想为我自己的服务创建一个基本定义文件。我在typings /globals中创建了一个目录,其中包含一个index.d.ts文件:

declare namespace foo {
    export function bar();
}
declare var baz: { some: number };

这只是为了确保如果定义不起作用,我不会浪费时间编写定义。

接下来,我通过添加引用标记将该index.d.ts文件包含在 typings /index.d.ts中:

/// <reference path="globals/psiewakacje/index.d.ts" />

令我惊讶的是,它在我项目的 Javascript 文件中不起作用。打字foo.baz.我没有得到任何明智的智能感知。

 

我能够获得的唯一 Intellisense 支持是当我通过以下方式在每个文件中导入这些服务时:

import * as InternalParser from '../services/InternalParser';

或者

var InternalParser = require('../services/InternalParser');

但这不使用 Typescript 的定义文件,只是给了我导出的属性。总的来说是一个不理想的结果。

 

我想知道如何让它正常工作。我查看了 node 和 lodash 的类型定义文件,它们也是这样做的:声明一个具有特定类型的变量/命名空间。但是,他们的定义在 Javascript 中有效,而我的则不行。如何正确处理?

4

3 回答 3

5

如果我创建一个tsconfig.json没有"allowJs": "true"编译器选项的文件,我可以重现所描述的行为。如果你希望你的 TypeScript 和 JavaScript 文件被视为一个项目,你应该有一个有tsconfig.json文件"allowJs": "true"和没有文件的jsconfig.json文件。

于 2018-08-28T02:46:05.193 回答
2

您不需要添加对typings/index.d.ts. 最简单的方法是将您的声明添加到项目中任何位置的全局声明文件中。

此外,不要使用varand namespace,只需使用interface.

例如。在您的目录的根目录中,您可以轻松添加

// index.d.ts
interface Foo {
  bar: () => void
}

interface Baz { some: number }
于 2016-08-18T20:52:17.787 回答
2

I had the same issue and discovered that the editor (VSCode) was looking in the wrong directory for the file, problem was solved by relative referencing the correct path, the specific path will vary, but in my example it was:

/// <reference path="../../typings/index.d.ts" />

index.d.ts contains the following:

/// <reference path="globals/core-js/index.d.ts" />
/// <reference path="globals/jasmine/index.d.ts" />
/// <reference path="globals/node/index.d.ts" />

and my directory/file structure appears as follows:

enter image description here

于 2016-09-05T09:32:16.930 回答