如何根据属性的类型用另一个接口扩展一个接口?

问题描述 投票:0回答:1

当联合类型属性是特定值时,我希望能够向我的接口添加额外的约束/类型。这在 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`?
typescript solid-js
1个回答
0
投票

你的意思是这样的吗?

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];
}
© www.soinside.com 2019 - 2024. All rights reserved.