reactjs - ממשק כללי שמרחיב ממשק אחר


ממשק הרכיב שלי

interface InputProps {
  value?:string,
  onChange?: (event: React.SyntheticEvent<HTMLInputElement>, data: string) => void;
}

אני רוצה לכתוב טיפוס גנרי שיכלול את כל התכונות מ-P ומ-WrappedFieldProps

interface FormComponent<P> extends WrappedFieldProps  {
// props from P
// props from WrappedFieldProps
}

/*
// import { WrappedFieldProps } from 'redux-form'
interface WrappedFieldProps {
    input: WrappedFieldInputProps;
    meta: WrappedFieldMetaProps;
}
*/

ולהשתמש בזה בפונקציה כללית shouldComponentUpdate

export function shouldFormFieldUpdate<P>(props: FormComponentProps<P>, nextProps: FormComponentProps<P>): boolean {
    const { input: { value }, meta: { valid, touched, error }, ...rest } = props;
    let result;
    // compare logic
    return result;
}

אבל קיבלתי שגיאת ts על משתנה rest: סוגי rest ניתן ליצור רק מסוגי אובייקט

תשובה #1

אתה יכול להגדיר סוג חיתוך עבור זה

type  FormComponent<P> = P & WrappedFieldProps ;
export function shouldFormFieldUpdate<P>(props: FormComponent<P>, nextProps: FormComponent<P>): boolean {
    const { input: { value }, meta: { valid, touched, error } } = props;
    let result;
    // compare logic
    return result;
}

המגבלה של הקוד למעלה היא שאתה לא יכול להשתמש ב-...rest. זו מגבלה נוכחית