比方说,我正在构建一个可重用的库,以在React应用程序中使用。此库查找具有特定属性和值的某些DOM元素。
例如,它查找具有“foo”属性的DIV,该属性可以等于“bar”或“baz”。
库和它的使用者都是用字体脚本编写的。
现在,当我尝试在我的消费者代码中实例化一个DIV元素时:
// consumer/Consumer.tsx
import * as React from 'react';
import 'library';
export const Consumer = () =>
我输入错误
Type '{ children: string; type: string; onClick: () => void; foo: string; }' is not assignable to type 'DetailedHTMLProps, HTMLButtonElement>'.
Property 'foo' does not exist on type 'DetailedHTMLProps, HTMLButtonElement>'.ts(2322)
(property) JSX.IntrinsicElements.button: React.DetailedHTMLProps, HTMLButtonElement>
// consumer/Consumer.tsx
import * as React from 'react';
import 'library';
declare module 'react' {
interface HTMLAttributes {
readonly foo?: 'bar' | 'baz';
}
}
export const Consumer = () =>
然而,我认为这真的应该在我的
图书馆的
代码,而不是消费者的代码。毕竟,定义合同是图书馆的工作,而不是消费者的工作。使用者应该能够从库中导入库定义的任何接口。
所以我尝试将声明移动到我的库代码中。我不确定把它放在哪里,所以我决定将它附加到index.t s文件中,该文件将导出库的所有组件:
// library/src/index.ts
export * from './LibraryComponent1.tsx';
export * from './LibraryComponent2.tsx';
// added declaration here:
declare module 'react' {
interface HTMLAttributes {
readonly foo?: 'bar' | 'baz';
}
}
不幸的是,这行不通。当我重新编译库并将其重新链接到我的消费者时,我会得到与上面相同的类型错误。
我试过了:
使用
declare namespace
而不是
declare module
正在添加
export
在前面
interface HTMLAttributes
在图书馆里
将声明放入其他文件
类型/索引.d.ts
SRC/Type
SRC/DIXX.D.TS
SRC/Test.TS
以各种方式导入库
导入“库”;
导入“library/src”;
导入“library/src/types”;
导入“库/类型”;
从“库”导入htmlattributes;
等。
我这里缺什么?有什么想法吗?