如何解决在没有类型断言的情况下在 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
和类型断言以进行更完整的类型检查。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。