当使用诸如XL之类的Grid尺寸道具时,如何在TypeScript中向其动态传递值?
例如,*更新示例说明
import Grid, { GridSize } from "@material-ui/core/Grid";
let value: GridSize = 12/4;
xl={value}
类型“数字”不可分配给类型“ GridSize”
如果我设置诸如
type gridSize = boolean | "auto" | 1 | 2 | 12 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined
不能将类型'number'分配给类型'boolean | “汽车” | 1 | 2 | 12 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | undefined'.ts(2769)
同一个问题,如何将数字转换为这种类型?
**在下面标记的答案很有帮助,最后我将其转换为GridSize并在边缘周围添加了一些单元测试。
让值= 12/4作为GridSize
已经定义了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
道具也接受boolean
和undefined
您还可以扩展GridSize
类型以包括这两个。
type NewGridSize = GridSize | boolean | undefined;
let size: NewGridSize = undefined;
- 编辑
Typescript没有这种高级的流量控制分析来假设这是 3
在这种情况下,您必须做一些肮脏的技巧才能将其投射到任何对象上。
let value: GridSize = 12/4 as any;
或者,您可以使类型卫士(不过这会过分杀伤)
function compute(value: any): value is 3 {
return value;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句