在没有类型断言的情况下在 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 (将#修改为@)