我遇到了为使用React PropTypes的instanceof check的第三方脚本编写Typescript定义的问题。具体为React TimeSeries Charts和PondJS。 (他们还没有创造任何东西,这就是为什么我不接受它)。
我为Pond定义了一个类似于
的Type文件declare module 'pondjs' {
type Timestamp = number;
/* other type aliases */
export class TimeSeries {
constructor(
options: {
[index: string]: any;
}
);
static is: (arg1: TimeSeries, arg2: TimeSeries) => boolean;
range: () => any;
min: (key: string) => number;
max: (key: string) => number;
name: () => any;
atTime: (timestamp: Timestamp) => any;
/* Other methods */
}
/* Other Class Definitions */
}
然后我的包装类使用它,就像这样
import { TimeSeries } from 'pondjs';
import { ChartContainer, ChartRow, LineChart } from 'react-timeseries-charts';
const timeSeries: TimeSeries = new TimeSeries({events: [{value: 15}]});
class myWrapper extends React.Component<Props, {}> {
render() {
return (
<ChartContainer>
<ChartRow>
<LineChart series={timeSeries} />
</ChartRow>
</ChartContainer>
);
}
这是一个极其简化的示例,但我的真实代码都正常工作,向页面绘制正确的内容,如果我传递错误的参数,Typescript无法编译。
但是,我从PropType's createInstanceTypeChecker
抛出的PropTypes中收到了一堆错误。
"Warning: Failed prop type: Invalid prop `series` of type `TimeSeries` supplied to `LineChart`, expected instance of `TimeSeries`."
问题在于LineChart
检查series: propTypes.instanceof(TimeSeries)
,但它当然是在内部导入Pond并检查&#34;真实&#34; TimeSeries
,而不是通过我的Typescript类型模块定义的那个。
当我进入createInstanceTypeChecker以查看正在进行的操作时,我可以看到,即使他们在技术上不是同一个类,(所以我猜PropTypes在其错误中是合理的)他们对于所有实际目的而言是相同的,这是我期望的Typescript产生的。
> expectedClass === props[propName].constructor
false
> props[propName] instanceof expectedClass
false
> props[propName].constructor
ƒ TimeSeries(arg) {
(0, _classCallCheck3.default)(this, TimeSeries);
this._collection = null;
// Collection
this._data = null;
// Meta data
if (arg ins…
> expectedClass
ƒ TimeSeries(arg) {
(0, _classCallCheck3.default)(this, TimeSeries);
this._collection = null;
// Collection
this._data = null;
// Meta data
if (arg ins…
但是,如果Typescript正在按照我的想法行事,我仍然希望instanceof check为true,如下所示
import { TimeSeries as _ts } from 'pondjs';
export class TimeSeries extends _ts {
/* same class, but with type extensions */
}
我认为React TimeSeries Charts可以解决&#34;通过检查道具的形状而不是使用的具体构造函数。但是,在为第三方库添加类型定义时,这也是一个非常常见的问题,对吧?由于我无法在任何地方找到类似的错误报告,我怀疑我必须遗漏一些明显的错误。
我不想完全禁用PropTypes。我要么发现我错误配置了这个类型声明文件并对其进行了更改,以便PropTypes检查instanceof工作,或者能够使用PropTypes可以做的不同同样简单的检查来更新React TimeSeries图表来说服自己Typescript增强类仍然基本上是同一个类,而不需要按键比较形状键。
版本: