打字稿:来自值的引用通用类型,用作其他地方的类型

时间:2020-05-04 15:18:31

标签: typescript typescript-generics

具有以下代码:

// file1.ts
interface X { ... } // Don't want to directly export this (private/internal)

// Assume LibInterface<T> is some random interface from an external library
export const func: (arg: LibInterface<X> => string) = ...;


// file2.ts (essentially the jest test file)
import { func } from './file1';

const x: X = ...;
const arg: LibInterface<X> = ...;

expect(func(arg)).toEqual(...);

在上面,我如何在第二个文件中引用类型X

使用类型Xjest-mock-extended的复杂用例:const mockX = mock<X>(...);

我已经搜索过此内容,也浏览了https://www.typescriptlang.org/docs/handbook/utility-types.htmlhttps://www.typescriptlang.org/docs/handbook/utility-types.html,但找到了解决方法。

1 个答案:

答案 0 :(得分:0)

您可以向该函数添加泛型吗?会是这样的:

// file1.ts
interface X { ... } // Don't want to directly export this (private/internal)

// Assume LibInterface<T> is some random interface from an external library
export const func: <T extends X = X>(arg: LibInterface<T> => string) = ...;


// file2.ts (essentially the jest test file)
import { func } from './file1';

const x: X = ...;
const arg: LibInterface<X> = ...;

expect(func(arg)).toEqual(...);