我正在尝试为现有的库编写 typescript 定义文件。该库 ( react-filepond ) 导出一个名为 File
的对象(如 usage example in the README 中所示)。
问题在于该库创建的另一个接口(interface)使用 JS File interface .
所以现在在我的 typescript 定义文件中,我必须以某种方式管理 File
类型的两个定义。我的解决方案是在定义文件中将库创建的对象声明为不同的名称,然后将其导出为"file"。
declare class FilePondFile extends React.Component<FilePondFileProps> { }
export { FilePondFile as File };
当我在自己的项目中使用该类型时,这看起来很不错。但作为 OSS 的支持者,我想通过 Definitely Typed 向社区提供这个定义。 repo 协议(protocol)。
他们的 linter 给了我一个错误,尽管这显然阻止了 my PR正在审核:
Error: C:/dev/DefinitelyTyped/types/react-filepond/index.d.ts:22:1
ERROR: 22:1 strict-export-declare-modifiers 'declare' keyword is redundant here.
See: https://github.com/Microsoft/dtslint/blob/master/docs/strict-export-declare-modifiers.md
乍一看,删除 class FilePondFile
前面的 declare
似乎很简单,但是,如果删除它,则会收到不同的错误:
A 'declare' modifier is required for a top level declaration in a .d.ts file.
所以我不知道如何处理这个矛盾。 Definely Typed 的维护者似乎没有时间提供帮助,因为我的 PR 刚刚被标记为“需要作者注意”,尽管我清楚地阐述了这个问题。
有人建议我可以做什么,以便不重复此定义文件中的 File
引用,同时还传递 Definely Typed linter?
最佳答案
The problem with that is that another one of the interfaces that this library creates utilizes the JS File interface.
还有另一种解决方案。
File
名称由从此模块声明和导出的类获取。
您必须在同一模块中描述FilePondItem
接口(interface),并且它必须具有与File
类型不同的file
属性 - 它必须引用 lib.dom.d.ts 中定义的全局 File
对象
export interface FilePondItem {
file: File;
TypeScript 类型是结构化的。您不必按名称引用全局 File
类型,您可以提供其定义,与 lib.dom.d.ts 中的定义兼容:
export interface FilePondItem {
file: Blob & {readonly lastModified: number; readonly name: string};
只要类型定义保持兼容,一切都会好起来的。
当然,也有缺点:它是重复的代码,更冗长,并且如果全局 File
,将来可能会与实际的 File
不兼容。 code> 类型更改(但我认为这不太可能)。
关于typescript - 如何处理 typescript 定义文件中的类型名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53876793/