从TypeScript中的对象属性继承通用值

时间:2019-01-16 12:22:17

标签: typescript typescript-typings

鉴于以下通用类型,是否有任何方法可以从必需的Props属性继承component类型,而不必将Props传递给Override

type Override<Props extends {} = {}> = {
  component: React.ComponentType<Props>
  props?: Props
}

我要实现的目标是

type AnchorProps = { [...] }
const Anchor: React.ComponentType<AnchorProps> = [...]
type ParagraphProps = { [...] }
const Paragraph: React.ComponentType<ParagraphProps> = [...]

type Overrides = {
  // i want to do this
  [tag in keyof JSX.IntrinsicElements]?: Override

  // rather than this
  a: Override<AnchorProps>,
  p: Override<ParagraphProps>,
  [...]
}

const overrides: Overrides = {
  a: {
    component: Anchor, // type is now `React.ComponentType<AnchorProps>`
    props: { [...] },  // type should inherit from `component` and be `AnchorProps`
  },
  p: {
    component: Paragraph, // type is `React.ComponentType<ParagraphProps>`
    props: { [...] },     // type should inherit `ParagraphProps`
  },
  [...]
}

2 个答案:

答案 0 :(得分:0)

否,您不能从Props类型继承component类型。使用TypeScript不可能做到这一点

如果您正在使用AnchorPropsParagraphProps的自定义界面,而不是标准的React.AnchorHTMLAttributes<HTMLAnchorElement>React.HTMLAttributes<HTMLParagraphElement>

,则无法直接执行此操作。

但是,如果您的Anchor组件采用与标准HTMLAnchorElement相同的道具,则仅需几行就可以实现所需的结果。

declare const Anchor: React.ComponentType<React.AnchorHTMLAttributes<HTMLAnchorElement>>
declare const Paragraph: React.ComponentType<React.HTMLAttributes<HTMLElement>>

type Overrides = {
  [tag in keyof JSX.IntrinsicElements]?: {
    component: React.ComponentType<JSX.IntrinsicElements[tag]>,
    props?: JSX.IntrinsicElements[tag]
  }
}

const overrides: Overrides = {
  a: {
    component: Anchor,
    props: {
      href: 'str', // ok
      broken: true // error, as expected
    }
  },
  p: {
    component: Paragraph
  }
}

答案 1 :(得分:0)

您需要告诉TypeScript内部元素和自定义道具之间的关系是什么。

interface OverriddenProps extends JSX.IntrinsicElements {
  a: AnchorProps;
  p: ParagraphProps;
}

创建您的Overrides映射类型:

type Overrides = {
  [Tag in keyof JSX.IntrinsicElements]?: {
    component: React.ComponentType<OverriddenProps[Tag]>;
    props: OverriddenProps[Tag]
  }
}

类型推断现在将正常工作。