typescript - 在没有类型断言的情况下在 TypeScript 中构建具有已知键的对象
问题描述
我想使用一组已知的键来“构建”一个对象,而不必使用类型断言。我在这个例子中缩小了问题的范围:
// Goal: I want build up a new object from these keys with shape: { first: 'hi', second: 'hi', third: 'hi' }
const keys = ['first', 'second', 'third'] as const
// This mapped type is correct for what I want to end with
type Goal = {
[Key in typeof keys[number]]: 'hi'
}
// ?? How to implement the actual object building without using type assertions?
// 1. If I start with an empty object and iteratate over keys I have to type assert the initial empty object:
const forEachEnd = {} as Goal
keys.forEach(key => {
forEachEnd[key] = 'hi'
})
// 2. If I reduce with an empty object I have to type assert the reduce initializer:
const reduceEnd = keys.reduce((acc, iter) => {
acc[iter] = 'hi'
return acc
}, {} as Goal)
我想避免使用类型断言,因为我试图避免any
在任何地方使用和类型断言以进行更完整的类型检查。
解决方案
推荐阅读
- python - Python 中是否有嵌套范围使用 for 循环的简写形式?
- angular - 需要通过angular ts代码将SSCC文件编译成CSS(不在cli中)
- lua - 如何从逻辑上理解 Lua 中的 table.sort 函数?
- c# - Asp.net MVC 应用程序并从数据库中获取 JSON 结果并将其输入到谷歌云翻译 v2 并获取 json 结果
- postgresql - pgAdmin 看不到 pgAgent 作业调度程序
- security - 在 vuex state + persistedState 插件中存储令牌是否安全?
- bash - 在集群范围的初始化脚本中从 dbfs 复制文件
- java - 如何在不使用 @PropertySources 注释的情况下使用 @ConfigurationProperties(prefix="foo.bar") 获取前缀属性
- amazon-web-services - 使用快照从单节点 Redshift 集群调整为两节点
- c# - C# Regex - 匹配某些字符,后跟数字/标识符