你如何在 React 中声明"干净元素"高阶组件的类型?



当前错误:

Argument of type 'typeof TextareaAutosize' is not assignable to parameter of type 'Component<{}, {}, any>'.
Property 'setState' is missing in type 'typeof TextareaAutosize'.

法典:

import clean from "clean-element";
import Textarea from "react-textarea-autosize";
const CleanInput = clean(Textarea);

和:

import * as React from 'react';
declare function clean<TPassedProps>(
component: React.Component<TPassedProps>
): React.ComponentType<TPassedProps>;
export default clean;

React.ComponentType<TPassedProps>替换React.Component<TPassedProps>应该可以消除直接错误。 但是,如果您真的想要为clean函数进行正确的键入,那就困难得多。 事实上,这实际上无法完成,因为clean返回的组件的行为取决于您分配给它的propTypes的类型,并且 TypeScript 不支持跟踪存储在已声明属性中的值的类型。 相反,您必须定义一个包装函数,该函数同时接受内部组件和propTypes对象,并计算新组件的 props 类型,以包括被剥离的 propclean以及传递到内部组件的 prop。 对于完整的解决方案,应检查clean是否未用于剥离内部组件实际需要的道具。 这是我想到的:

import * as React from "react";
import * as PropTypes from 'prop-types';
import clean from "clean-element";
type RequiredKeysOf<T> =
{[K in keyof T]-?: {[P in K]?: T[K]} extends {[P in K]: T[K]} ? never : K}[keyof T];
const ERROR_SYMBOL = Symbol();
interface Cannot_clean_required_props<K extends keyof any> {
[ERROR_SYMBOL]: undefined;
}
function cleanWithPropTypes<TPassedProps,
TPropTypes extends React.ValidationMap<any> &
(keyof TPropTypes & RequiredKeysOf<TPassedProps> extends never ? {} :
Cannot_clean_required_props<keyof TPropTypes & RequiredKeysOf<TPassedProps>>)>(
component: React.ComponentType<TPassedProps>, propTypes: TPropTypes):
React.ComponentType<PropTypes.InferProps<TPropTypes> &
Pick<TPassedProps, Exclude<keyof TPassedProps, keyof TPropTypes>>> {
let cleaned = clean(component);
cleaned.propTypes = propTypes;
return cleaned;
}

最新更新