TypeScript has a powerful inference system, which allows you to not specify the generic parameter manually but rather have it assigned based on the type of a runtime parameter. For React + TypeScript, this looks like:
type MyComponentProps<T extends Record<string, unknown>> = {
value: T;
handleChange: (value: T) => void;
};
const MyComponent = <T extends Record<string, unknown>>(
props: MyComponentProps<T>
) => {
return null;
};
class MyOtherComponent<
T extends Record<string, unknown>
> extends React.Component<MyComponentProps<T>> {
render() {
return null;
}
}
// This works
<MyComponent
value={{ a: "hi", this: { is: "a", test: true } }}
handleChange={(val) => {
console.log("val.a =", val.a, "val.this =", val.this);
}}
/>
<MyOtherComponent
value={{ a: "hi", this: { is: "a", test: true } }}
handleChange={(val) => {
val.a = val.this.is;
}}
/>
// This fails
<MyComponent
value="not a Record<string, unknown>"
handleChange={() => {}}
/>
CodeSandbox
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…