当联合类型属性是特定值时,我希望能够向我的接口添加额外的约束/类型。这在 Typescript 中可能吗?
作为一个具体的例子......如果我有一个类型
TypographyProps
并且它有一个联合类型的 variant
属性。如何使用 variant
属性来扩展 TypographyProps
以包含另一种类型?
export interface TypographyProps extends ParentProps {
variant?: "h1" | "h2" | "h3" | "p" | "span";
color?: keyof Theme["colors"];
spacing?: Theme["spacing"];
wrap?: boolean;
}
// How can I add in the type def for each type `JSX.IntrinsicElements["h2"]`, etc... based on `variant`?
你的意思是这样的吗?
type Variant = "h1" | "h2" | "h3" | "p" | "span";
// alternatively:
// type Variant = keyof JSX.IntrinsicElements;
export interface TypographyProps<V extends Variant > extends ParentProps {
variant?: V;
def: JSX.IntrinsicElements[V];
}