import { Equal, Expect } from "../helpers/type-utils";
interface Button<T> {
value: T;
label: string;
}
interface ButtonGroupProps<T> {
buttons: Button<T>[];
onClick: (value: T) => void;
}
const ButtonGroup = <T extends string>(props: ButtonGroupProps<T>) => {
return (
<div>
{props.buttons.map((button) => {
return (
<button
key={button.value}
onClick={() => {
props.onClick(button.value);
}}
>
{button.label}
</button>
);
})}
</div>
);
};
<>
<ButtonGroup
onClick={(value) => {
type test = Expect<Equal<typeof value, "add" | "delete">>;
}}
buttons={[
{
value: "add",
label: "Add",
},
{
value: "delete",
label: "Delete",
},
]}
></ButtonGroup>
</>;
It is important to use <T extends string>
, otherwise Typescript cannot infer the exact value
The type flow down from ButtonGroup to Button, infer the value of `add | delete`, then bubble up to ButtonGroupProps, set onClick(value: T); then bubble up to ButtonGroup component, set generic type T.
标签:Typescript,Inference,Generic,value,label,ButtonGroup,ButtonGroupProps,type From: https://www.cnblogs.com/Answer1215/p/17625038.html