【问题标题】:WithStyles<typeof styles> in Material UI?材质 UI 中的 WithStyles<typeof 样式>?
【发布时间】:2020-05-02 08:02:03
【问题描述】:
import { WithStyles, createStyles } from '@material-ui/core';

const styles = (theme: Theme) => createStyles({
  root: { /* ... */ },
  paper: { /* ... */ },
  button: { /* ... */ },
});

interface Props extends WithStyles<typeof styles> {
  foo: number;
  bar: boolean;
}

我直接从 Material UI 文档中获取上述示例。我的问题是,为什么文档建议使用WithStyles&lt;typeof styles&gt; 而不是WithStyles&lt;string&gt;。请有人深入解释 typeof 样式的评估结果是什么?据我了解,这将是一个字符串?

【问题讨论】:

    标签: reactjs typescript material-ui typescript-typings


    【解决方案1】:

    看来我在这里回答了我自己的问题。

    如果我们在打字稿文件中有以下内容

    const styles = {a: 1, b: 2, c: 3};
    

    然后我们可以使用以下语法声明另一个我们希望具有与样式相同的属性名称的对象

    const stylesV2: typeof styles = {a: 10, b: 20, c: 24}
    

    这样,如果 styleV2 中缺少样式中存在的属性,TypeScript 将抱怨缺少属性“x”......但必需。

    因此在WithStyles&lt;typeof styles&gt; 的情况下,我们希望使用当前包含在样式中的任何内容来转换类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 2019-10-09
      • 1970-01-01
      • 2020-09-21
      • 2018-10-08
      • 2019-06-02
      • 1970-01-01
      相关资源
      最近更新 更多