I have a generic component with a generic type, which extends required id property GenericComponent = <T extends { id: number }>. Also I have the interface where id is not required:
interface DataInterface {
id?: number;
}
In the <App /> component I render it, checking for existing id, but TS expectedly throws the error:
Type 'DataInterface' does not satisfy the constraint '{ id: number; }'.
Property 'id' is optional in type 'DataInterface' but required in type '{ id: number; }'
I see one way to avoid this: to create a new interface based on my interface and set id as required, like this:
interface DataWithIdInterface extends DataInterface {
id: number
}
But maybe is there any better way?
The example:
interface DataInterface {
id?: number;
}
type Props<T> = {
data: T;
};
const GenericComponent = <T extends { id: number }>({ data }: Props<T>) => (
<div>{data.id}</div>
);
const App = () => {
const data = {
id: undefined
};
if (data.id) {
// error here
return <GenericComponent<DataInterface> data={data} />;
}
return null;
};
T extends { id?: number }>instead ofT extends { id: number }if it's okay foridto be optional?