【发布时间】:2022-11-15 05:54:37
【问题描述】:
我有一个组件,它采用一组选项,定义如下:
interface Props {
options: {
label: string;
value: string;
}[]
}
function MyComponent(props: Props) {...}
并像这样实现:
<MyComponent
options={[
{ label: "Right Hand", value: "RIGHT" },
{ label: "Left Hand", value: "LEFT" }
]}
/>
在这个例子中,我提供了选择惯用手的选项,并且我已经为此定义了一个类型:
type DominantHand = "RIGHT" | "LEFT"
是否可以让MyComponent灵活地指定选项的类型?
我试过像下面这样完成这个,但显然这里的语法不正确:
type DominantHand = "RIGHT" | "LEFT"
type Gender = "MALE" | "FEMALE"
interface Props {
options<T>: { // this syntax is wrong
label: string;
value: T;
}[]
}
function MyComponent(props: Props) {...}
...
<MyComponent
options<DominantHand>={[ // <--- this syntax is wrong
{ label: "Right Hand", value: "RIGHT" },
{ label: "Left Hand", value: "LEFT" }
]}
/>
<MyComponent
options<Gender>={[ // <--- this syntax is wrong
{ label: "Male", value: "MALE" },
{ label: "Female", value: "FEMALE" }
]}
/>
有没有办法做到这一点?
【问题讨论】:
标签: reactjs typescript typescript-generics