typescript - 打字稿确保类型包含子字符串
问题描述
我定义了一个SizeType
并准备设置设备媒体查询类型检查。是否有可能不是string
仅在 DeviceSize 上使用,而是必须包含子字符串min-width: ...
,然后将其余字符串限制为size
属性值?
type SizeType = 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
type Size = { [size in SizeType]: string };
type DeviceSize = { [size in SizeType]: string };
interface Theme {
device: Required<Partial<DeviceSize>>;
}
const size: Size = {
sm: '576px',
md: '768px',
lg: '1024px',
xl: '1440px',
xxl: '2560px',
};
const theme: Theme = {
device: {
sm: `(min-width: ${size.sm})`,
md: `(min-width: ${size.md})`,
lg: `(min-width: ${size.lg})`,
xl: `(min-width: ${size.xl})`,
xxl: `(min-width: ${size.xxl})`,
},
}
使用当前设置,这将通过检查:
const theme: Theme = {
device: {
sm: `(min-width: ${size.sm})`,
md: `(min-width: ${size.md})`,
lg: `(min-width: 100)`,
xl: `(min-width: 220px)`,
xxl: `abc`,
},
}
解决方案
当然,只需将您的字符串类型声明为具有您想要的模式的模板文字。
type DeviceSize = { [size in SizeType]: `(min-width: ${string})` };
现在应该会给您预期的错误:
const theme: Theme = {
device: {
sm: `(min-width: ${size.sm})`,
md: `(min-width: ${size.md})`,
lg: `(min-width: 100)`,
xl: `(min-width: 220px)`,
xxl: `abc`,
// Type '"abc"' is not assignable to type
// '`(min-width: ${string})`'.(2322)
},
}
甚至:
`(min-width: ${number}px)`
如果你想验证它是一些px
单位。
推荐阅读
- sql - 使用 table1 更新 table2 中的值
- php - 如何基于具有多个孩子的数组创建路径
- bash - 如何使用 exec 执行任意查找命令
- blogger - 在博客上的指定标签上显示小部件
- python - 将高分保存在游戏的文本文件中
- javascript - 如何将 RxPy 数据流发送到前端 javascript
- jenkins - 作业结果是 Post Script 结果
- javascript - 创建一个函数,以 500 平方英尺的增量将基价提高 10%
- python - Django 不与 sqlite3 同步(官方投票教程)
- google-app-engine - Safari 'origin is not allowed' 阻止 AppEngine 身份感知代理 https://accounts.google.com/o/oauth2/v2/auth