【问题标题】:How to destructure a typescript interface and use it in another interface?如何解构一个打字稿界面并在另一个界面中使用它?
【发布时间】:2021-09-26 04:35:54
【问题描述】:

我正在探索打字稿模式,但不确定是否可以完成。

基本上,在我的 React 组件中,我有以下接口:

interface IPaper {
  className?: string;
  children: React.ReactNode;
  elevation?: 'low' | 'medium' | 'high';
}

虽然上面的例子很好,但我想探索一些更智能、更容易维护的东西。具体来说,使用当前在ThemeParameters 示例中找到的键,如下所示:

  interface ThemeParameters extends StorybookIntegration {
    ...
    
    elevation: {
      low: string;
      medium: string;
      high: string;
    };
  
    ...
  }

实际上,我的组件看起来类似于下面的示例,组件的elevation 属性与我的ThemeParameters 中的任何高程设置相耦合。这样,如果我修改了我的主题,它将被组件上的界面自动捕获。

interface IPaper {
  className?: string;
  children: React.ReactNode;
  elevation?: ThemeParameters['elevation'];
}

const Paper = ({ className, children, ...props }: IPaper): JSX.Element => (
  <Wrapper className={className} elevation="low" {...props}>
    {children}
  </Wrapper>
);

const Wrapper = styled.div<{ elevation: string }>`
  box-shadow: ${({ theme, elevation }) => theme.elevation[elevation]};
`;

不幸的是,这并不完全有效。关于如何使用打字稿进行设置的任何聪明想法?


解决方案

使用以下最佳答案中的建议的示例。

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:
    ThemeParameters['elevation']
    

    是这种类型吗:

    {
      low: string;
      medium: string;
      high: string;
    }
    

    所以你想要对象的键。这就是keyof 的用途:

    keyof ThemeParameters['elevation']
    

    这是什么类型:

    'low' | 'medium' | 'high'
    

    Playground

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2016-10-07
      • 2021-12-24
      • 1970-01-01
      • 2018-02-04
      • 2019-11-23
      • 2018-04-08
      • 2016-06-21
      • 1970-01-01
      相关资源
      最近更新 更多