typescript - 如何在打字稿中获得严格的值类型?
问题描述
例如,我有一个函数签名如下:
declare function foo<T>(input: T): T;
我希望它返回严格类型的输入对象而不手动设置模板类型:
const bar = foo({ str: 'foo', bool: true })
的预期类型bar
是:{ str: 'foo', bool: true }
而不是{ str: string; bool: boolean }
.
解决方案
从 TypeScript 3.4 开始,编写
const bar = foo({ str: 'foo', bool: true } as const)
推荐阅读
- sql - 如何避免在 SQL Query 中进行硬编码
- python - 在 QTreeView 中添加一个 Widget (QProgressbar) 作为 childItem
- javascript - 如何在 kendo TreeList 中选择父节点时选择所有子节点?javascript
- bash - 如何对特定长度进行子字符串化并将该子字符串文本附加到unix中的行尾
- micropython - BLE FLAG_WRITE 没有响应?
- javascript - 有没有办法以角度收听变化检测完成事件
- php - 如何禁用和启用有条件的按钮
- python - np.where 计算不正确?
- javascript - 将嵌套数组导出为 xlsx 格式
- r - 阿尔法美学显示箭头的骨架而不是简单的形状 - 如何防止它?