网站搜索

typescript - 在自定义定义中引用全局声明的命名空间类型


这个话题有一个以前的问题,但没有发布答案:

如何导入一个顶级元素是未导出的命名空间的 Typescript 类型定义文件?

我想为 testdouble-jest 创建一个类型,但它导出函数的第二个参数是全局 jest 实例,该实例在 @types/jest 中声明为顶级声明的命名空间:

declare namespace jest {
  mock(): something
  // ...
}

编辑:这里是类型:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jest/index.d.ts

我如何在我的 test-double.d.ts 声明中引用这个全局对象?我的声明如下,但只取得了部分成功:

/// <reference types="jest" />
// do i actually need the above directive?

declare module "testdouble-jest" {
  import * as td from "testdouble"; // the testdouble stuff works
  export type TestdoubleJest = typeof td & {
    mock: typeof jest.mock;  // this actually appears to work
  };
  function setupTestdoubleJest(
    testdouble: typeof td,
    jest: typeof jest // this just resolves to any
  ): TestdoubleJest;

  export = setupTestdoubleJest;
}

如果有人知道如何做到这一点,我将非常感激!

编辑 2:在 DefinitelyTyped 上有一些例子,人们要么在增强 ‘jest‘ 命名空间,要么使用其成员(就像我使用 jest.mock 那样),但我找不到一个例子是指实际的全局 jest 对象。

  • https://github.com/DefinitelyTyped/DefinitelyTyped/blob/39580cb71a89cde61d217d8d418347c58a2f2103/types/jest-json-schema/index.d.ts

答案#1

替换

/// <reference types="jest" />

与

/// <reference types="@types/jest" />

这对我有效。