如何用自定义定义覆盖库定义的类型



我正在Typescript 3.8中构建一个应用程序。我想使用的库有一个导出的类型,该类型使用模板文本字符串,这只在Typescript 4.1+中受支持,并导致我的构建失败。

我想用我自己的类型替换库的类型,创建所有可能值的并集,以与我的typescript版本兼容的方式实现相同的结果。

// Library's exported type
export declare type AlignedPlacement = `${Side}-${Alignment}`;
// My new type
type AlignedPlacement = 'top-start' | 'top-end' | 'right-start' | 'right-end' | 'bottom-start' | 'bottom-end' | 'left-start' | 'left-end';

我曾尝试过用模块增强来实现这一点,但我遇到了一个重复标识符错误——它似乎只适用于重写接口,而不适用于类型。

declare module '@floating-ui/core' {
type AlignedPlacement =
| 'top-start'
| 'top-end'
| 'right-start'
| 'right-end'
| 'bottom-start'
| 'bottom-end'
| 'left-start'
| 'left-end';
}

我发现了一个使用patch-package解决此问题的示例(https://github.com/floating-ui/floating-ui/issues/1584#issuecomment-1071501851(,但我真的不想为了解决这个问题而在我的应用程序中引入另一个依赖项。感觉在Typescript中应该是可能的。

任何帮助都将不胜感激-谢谢!

我最终使用了问题中链接所描述的patch-package解决方案

https://github.com/floating-ui/floating-ui/issues/1584#issuecomment-1071501851

最新更新