typescript - 我想用打字稿上的其他类型将类型保护为 const
问题描述
如果有更合适的标题,请告诉我。
例如,我在 AB 类型中添加 C。我希望 ABSentences 中的类型检查错误。
示例代码
type AB = {
A?: any
B?: any
}
const ABSentences: { [key in keyof Required<AB>]: string } = {
A: 'this is A.',
B: 'this is B.',
} as const
我想用来type AB
保护ABSentences
.
你有什么好主意吗?
缺席的实际类型
const ABSentences: {
A: string;
B: string;
}
期望类型的 ABSentences
const ABSentences: {
A: 'this is A.';
B: 'this is B.';
}
解决方案
const ABSentences = {
A: 'this is A.',
B: 'this is B.',
} as const
如果您正在使用,只需删除显式类型注释as const
推荐阅读
- vimeo - 当调用“apiready”事件时,无法访问视频的持续时间。
- python - python 机械化 400 错误请求
- javascript - Jquery 数据表导出到 Excel,想要将一些数字列转换为字符串
- python - 正则括号 Python 的非捕获版本
- r - 在 Mac 中使用 R 读取 .xpt 文件
- python - 声明一个 numpy 矩阵的简洁方法
- android - 浮动操作按钮在 Android Studio 中的 Google 地图上不可见
- java - 打印 2 个最大值的索引
- fiware - fiware perseo 是否支持 esper 时间间隔?
- javascript - 自定义 Angular 6 材质日期选择器