首页 > 解决方案 > 使用泛型扩展模块

问题描述

在打字稿中,是否可以在某些消费代码中扩充模块时将泛型参数更新为类型。

例如,如果我的模块看起来像

// my-module.ts

export type FuncProps<T extends string = "foo"> = Record<T, number>;

export function myFunc(props: FuncProps) {
  // do something...
}

(我从库中导出函数和类型......)

然后,在使用此模块的代码中的某处,我有类似...

// types.d.ts

import { FuncProps } from 'my-module';

declare module "my-module" {
  type FuncProps<"bar">
}

在消费项目的另一个地方

import { myFunc } from 'my-module';

myFunc({ bar: 100 })

现在该函数接受bar而不是foo因为我们在消费项目中的声明。

这可能吗?如果是这样,我需要对此处给出的代码示例进行哪些更改才能使其正常工作?

标签: javascripttypescripttypescript-generics

解决方案


推荐阅读