typescript - TypeScript:断言对象文字具有彼此相等的键值
问题描述
在 TypeScript 中是否可以断言const
对象文字是以每个键等于其值的方式制作的?
换句话说:
// Good
const testIds: KeyEqualsValue = {
foo: 'foo'
} as const
// Bad
const testIds: KeyEqualsValue = {
foo: 'bar' // Error
} as const
解决方案
不是单一类型,你可以用一个函数来做到这一点:
function propAsValue<T extends { [P in keyof T]: P }>(o: T) {
return o;
}
const testIds = propAsValue({
foo: 'foo'
});
const testIds2 = propAsValue({
foo: 'bar'
});
或者使用内联函数,如果你想简洁并让每个人都感到困惑:
const testIds = (<T extends { [P in keyof T]: P }>(o: T) => o)({
foo: 'foo'
});
尽管我不确定您的用例是什么,但使用Object.keys
.
推荐阅读
- google-analytics - 立即跟踪页面放大器的分析
- javascript - 显示 Sweet alert ViewBag 值
- php - 如何从 laravel 测试用例测试封装在 nova::whenServing() 中的 laravel 观察者代码
- c - 在 C、Linux 中使用 LD_PRELOAD 拦截克隆
- python - 如果您使用的是 Microsoft Windows,则在尝试将作业分配给多个 CPU 时启动不需要的主程序副本
- node.js - 如何成功地将 dialogflow 与 node.js 集成
- gitlab-ci - Github Actions 中合并结果的管道?
- python - XlsxWriter 对齐设置不起作用
- ruby-on-rails - 运行 Rspec 系统测试时,API 不工作
- python - 在 Python 中关闭时删除临时文件