'How to get type with all properties from other type property when only common props is defined as generic type
Is it possible it typescript to define a type which will recognize properties of another type property when specifying JSX? I tried as per below:
type LocationItem = {
id: number;
lat: number;
lng: number;
city: string;
countryCode: string;
};
type BaseFieldProps<T> = {
name: string;
value?: T;
setValue?: (value: T) => void;
getValue?: (name: string) => T;
};
type LocationFieldProps = BaseFieldProps<LocationItem> & {
required?: boolean;
isActive?: boolean | ((value: Location) => boolean);
};
const LocationField = (props: LocationFieldProps) => {
return <div />;
};
type MultiFieldBaseProps<T> = {
Field: React.FC<BaseFieldProps<T>>;
count: number;
};
type MultiFieldProps<T> = MultiFieldBaseProps<T> &
React.ComponentProps<MultiFieldBaseProps<T>['Field']>;
export const MultiField = <T,>({
Field,
count,
name,
setValue,
getValue,
value,
...fieldRelatedProps
}: MultiFieldProps<T>) => {
return (
<>
{[...new Array(count)].map((_, index) => (
<Field key={index} name={name + index} {...fieldRelatedProps} />
))}
</>
);
};
export const App = () => {
return (
<MultiField
Field={LocationField}
count={10}
name="someLocation"
isActive={true} // won't be recognized
required={true} // won't be recognized
/>
);
};
The idea is for MultiField to receive properties of functional component passed as property Field. Is there any typescript trick to do that, as I believe MultiField only gets properties of Field that belongs to BaseFieldProps but have no clue about additional props field could have (in this case required,isValid). Any chance to get them as well in MultiField component as ...fielRelatedProps
Field: React.FC<BaseFieldProps<T>>;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
