I'm writing a React project using TypeScript, and I want to create a new component that takes a value that is an array of objects, and can create new objects to add to this array. When creating a new object, I want it to start with a blueprint that I define, that already includes some default values for some of the object's fields.
My problem is that I can't seem to get the blueprint to follow the value's generic type. The below (very simplified example) code is perfectly fine according to TypeScript:
type Props<T extends object> = {
value: Array<T>;
blueprint: T;
};
function MyComponent<T extends object>({}: Props<T>) {
return <div></div>;
}
function ParentComponent() {
return <MyComponent
value={[{ foo: "bar" }, { foo: "oof"}]}
blueprint={{ boo: "faz" }} // This doesn't throw a type-error, but I would like it to.
/>
}
I'd like TypeScript to throw a type-error when the blueprint
prop doesn't look like an object in the value
array. I've tried doing this by using a second generic type that extends or equals the first, but I've not managed to get to a solution.
T
. Is is supposed to usevalue
orblueprint
? Since it can't, it uses the lowest common denominator. If you look at the type that TypeScript assigns to those properties, you'll that the type ofblueprint
andvalue
are{foo: string; boo?: undefined;} | boo: string; foo?: undefined;}
I think there may be a way to specify what the call site is, and it means creating a wrapper function, but I can't remember exactly how to do it.return <MyComponent<{foo: string}>