【问题标题】:Typescript dynamically assign generic type based on a variableTypescript 根据变量动态分配泛型类型
【发布时间】:2021-07-13 10:01:08
【问题描述】:

我想使用类型(或接口)来扩展 React 组件。

定义:

type CoreProps<T> = {
  htmlElement?: 'article' | 'aside' // ...
} & React.HTMLAttributes<T>

希望使用:

type MyComponentProps = {
  myComponentFirstProp: string
  // ...
}

const MyComponent = ({ 
  htmlElement, 
  myComponentFirstProp,
  ...props
}: MyComponentProps & CoreProps): JSX.Element => {
  // ...
}

我知道我可以将&lt;T&gt; 替换为HTMLElement,但有没有办法根据htmlElement 传入的MyComponent 中的输入输入CoreProps?

【问题讨论】:

  • 你的意思是CoreProps应该和htmlElement有相同的类型吗?
  • @DTrombett 我的意思是如果htmlElement==='article' 在MyComponent 中,那么CoreProps 将是... &amp; React.HTMLAttributes&lt;HTMLArticleElement&gt;
  • 你有没有尝试写类似:const MyComponent = &lt;T extends 'article' | ...&gt;({...}: MyComponentProps &amp; CoreProps&lt;T&gt;): JSX.Element =&gt; {}?
  • @gpichot 你的解决方案不会在` { ... } & React.HTMLAttributes`中实现&lt;T&gt;

标签: reactjs typescript types


【解决方案1】:

有JSX.IntrinsicElements类型,可以获取相关的HTMLAttributes,这样就可以了。

interface CoreProps<T> {
  htmlElement: T;
}

interface MyComponentProps {
  myComponentFirstProp?: string;
}

const MyComponent = <T extends keyof JSX.IntrinsicElements>(
  props: CoreProps<T> & JSX.IntrinsicElements[T] & MyComponentProps
): JSX.Element => {
  ...
};

<MyComponent htmlElement="img" src="." />; // OK
<MyComponent htmlElement="a" href="." />; // OK
<MyComponent htmlElement="article" />; // OK
<MyComponent htmlElement="a" src="." />; // Error, no 'src' attribute in <a> element

如果要相应类型的属性

import { DetailedHTMLFactory, ReactHTML } from 'react';

type EleAttributes<
  T extends keyof ReactHTML
> = ReactHTML[T] extends DetailedHTMLFactory<infer R, infer P> ? R : never;

EleAttributes<'input'>
EleAttributes<'aside'>
...

更新

基于您的示例:

type CoreProps<T extends keyof JSX.IntrinsicElements> = {
  htmlElement?: T;
} & JSX.IntrinsicElements[T];

type ComponentProps = {
  display?: string;
};

const Component = <T extends keyof JSX.IntrinsicElements>({
  htmlElement,
  display,
  style,
  children,
  ...props
}: ComponentProps & CoreProps<T>) => {
  const styles = {
    ...style,

    display,
    // more ...
  };

  // Set default 'div' when htmlElement is undefined
  return React.createElement(
    htmlElement || 'div',
    {
      style: styles,
      ...props,
    },
    children
  );
};

【讨论】:

  • 这与我声明类型和组件的方式不同。 MyComponent、htmlElement里面不能设置。
  • 嗯?我知道你的意思是什么,你能显示代码吗?
  • Type '"div"' is not assignable to type 'T'. '"div"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'keyof IntrinsicElements'. 这是我在尝试实施您的解决方案时遇到的错误。
  • 我想看看你的代码的细节,因为它在我的身上完美运行
猜你喜欢
  • 1970-01-01
  • 2018-09-19
  • 2020-05-22
  • 2018-05-06
  • 2021-11-16
  • 2020-04-04
  • 2019-05-30
  • 1970-01-01
  • 2018-11-03
相关资源
最近更新 更多