【问题标题】:How do you dynamically set the value for the MaterialUI grid size prop in TypeScript?如何在 TypeScript 中动态设置 MaterialUI 网格大小道具的值?
【发布时间】:2020-05-28 14:00:45
【问题描述】:

当使用 Grid size 属性时,例如 XL,如何在 TypeScript 中动态传递一个值?

例如, *更新示例说明

import Grid, { GridSize } from "@material-ui/core/Grid";
let value: GridSize = 12/4;
xl={value}

类型 'number' 不能分配给类型 'GridSize'

如果我设置一个类型,例如,

type gridSize = boolean | "auto" | 1 | 2 | 12 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined

类型“数字”不可分配给类型“布尔|” “汽车” | 1 | 2 | 12 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |未定义'.ts(2769)

同样的问题,如何将数字转换为这种类型?

** 标记在下方的答案有帮助,最后我将其转换为 GridSize 并在其周围添加了一些单元测试以用于边缘情况。

让值 = 12/4 as GridSize

【问题讨论】:

    标签: typescript material-ui


    【解决方案1】:

    已经定义了GridSize 类型,可以在代码中使用

    export type GridSize = 'auto' | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
    

    示例

    import Grid, { GridSize } from "@material-ui/core/Grid";
    
    const App = () => {
      let size: GridSize = 1;
    
      return <Grid xl={size}>
      </Grid>
    }
    
    render(<App />, document.getElementById("root"));
    

    --编辑

    我看到 xl 属性也接受 booleanundefined

    您还可以扩展GridSize 类型以包含这两个。

    type NewGridSize = GridSize | boolean | undefined;
    
    let size: NewGridSize  = undefined;
    

    --编辑

    Typescript 没有如此高级的流控制分析来假设这是3

    在这种情况下,您必须做一些肮脏的伎俩才能将其投射到任何地方。

    let value: GridSize = 12/4 as any;
    

    或者你可以做 typeguard (虽然这会有点过分)

    function compute(value: any): value is 3 {
      return value;
    }
    

    【讨论】:

    • 这是同样的问题,类型“数字”不可分配给类型“GridSize”.ts(2322)
    • 你用的是什么打字稿版本?
    • "打字稿": "^3.7.5"
    • 我将您的评论标记为解决方案,因为它让我成功了一半。然后我因为你的 cmets 而找到了这个,并把我一路带到了那里。 stackoverflow.com/questions/51971705/…
    • 稍微更新了答案。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2017-05-17
    • 2021-04-16
    • 2011-03-17
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    相关资源
    最近更新 更多