首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript:从值中引用泛型类型以用作其他地方的类型

Typescript:从值中引用泛型类型以用作其他地方的类型
EN

Stack Overflow用户
提问于 2020-05-04 23:18:32
回答 1查看 23关注 0票数 0

代码如下:

代码语言:javascript
复制
// 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上找过了,但还是找到了解决方案。

EN

回答 1

Stack Overflow用户

发布于 2020-05-04 23:23:10

您是否能够将泛型类型添加到函数中?应该是这样的:

代码语言:javascript
复制
// 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(...);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61595632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档