首页 > 解决方案 > 在没有类型断言的情况下在 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在任何地方使用和类型断言以进行更完整的类型检查。

标签: typescriptjavascript-objectsmapped-types

解决方案


推荐阅读