【问题标题】:How to copy properties from one object to another in typescript如何在打字稿中将属性从一个对象复制到另一个对象
【发布时间】:2021-03-02 19:20:15
【问题描述】:

我正在寻找一种类型安全的方法来在对象之间复制属性。我的代码在 javascript 中工作,我正在尝试将其转换为打字稿,但是我无法让它工作。我收到Type '' is not assignable to type 'undefined'.(2322)

有人可以帮助我了解是否可以做我想做的事情以及我错过了什么?

enum Kind { PRIMARY, SECONDARY };
enum Size { SMALL, MEDIUM };

type IconProps = { kind: Kind; size: Size; };
type ButtonProps = { id: string; text: string; onClick: () => void; };
type Props = ButtonProps & IconProps;

function iconComponent(props: Partial<IconProps>)  {}
function buttonComponent(props: Partial<ButtonProps>)  {}

const isIconProp = (key: string): key is keyof IconProps =>  /^(kind|size)$/.test(key);
const isButtonProp = (key: string): key is keyof ButtonProps => /^(id|text|onClick)$/.test(key);

function initComponents(props: Partial<Props>) {
  // Default values
  const icon: Partial<IconProps> = {
    kind: Kind.PRIMARY
  };
  const button: Partial<ButtonProps> = {
    id: 'button'
  };

  // How to iterate through keys and assign properties to respective objects?
  Object.keys(props).forEach(key => {
      // Why is this not working?
      if (isIconProp(key)) {
        icon[key] = props[key]
      } 
      
      if (isButtonProp(key)) {
        button[key] = props[key];
      }

      // This works
      if (key === 'kind') {
        icon.kind = props.kind;
      }

      if (key === 'onClick') {
        button.onClick = props.onClick;
      }
  });

  return {
      root: buttonComponent(button), 
      child: [iconComponent(icon)]
    };
}

【问题讨论】:

  • 我认为您无法在运行时 key is keyof IconProps 中执行此操作,因为这不是实际的 javascript。您可以找到它们是图标道具还是按钮道具的一种方法是检查属性名称。例如。是道具种类,或者尺寸,那么你就知道它的图标道具了。
  • @medzz123 谢谢.. 正如我所提到的,代码在运行时运行良好。我只是想用打字稿对代码进行静态类型检查。我已经更新了代码以使其清晰。

标签: javascript reactjs typescript react-typescript


【解决方案1】:

我想出了以下方法,目前看来已经足够了。如果有更好的方法,请发表评论。

const mapTo = <T, S extends T, K extends keyof T>(target: T, source: S, key: K): void => {
    target[key] = source[key];
};


Object.keys(props).forEach(key => {
   if (isIconProp(key)) {
       mapTo(icon, props, key);
   } 
      
   if (isButtonProp(key)) {
       mapTo(button, props, key);
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2014-12-08
    • 2012-03-10
    • 2016-12-21
    • 2018-02-01
    相关资源
    最近更新 更多