如果我有一个打字稿类型由密钥:在打字稿合并类型(添加键现有keyof型)
const anObject = {value1: '1', value2: '2', value3: '3'}
type objectKeys = keyof typeof anObject
,然后我想密钥添加到该类型的,同时保留当前键我该如何去做呢?
例如,如果我想添加键“get_value1”,“get_value2”,“get_value3”的类型“objectKeys”
最后,我希望有一个类型,看起来像这样:
type objectKeys = keyof anObject + 'get_value1', 'get_value2', 'get_value3'
而不必手动定义以'get_'为前缀的键,我知道我可以输入键来创建这个对象 - 但是这对我的用例来说是不可行的。我只是想添加一些可能或可能不存在的键'objectKeys'
我也知道我可以创建一个通用或任何允许任何键值的类型,但是我必须知道实际的键名。它不帮助我允许请求对象的任何密钥,我需要现有的密钥+我想要添加的密钥。
感谢您的任何帮助。
增加了净度:
const anObject = {val1: '1', val2: '2'}
type objectKeys = keyof typeof anObject
Object.keys(anObject).forEach(key => {
const getAddition = `get_${key}`
anObject[getAddition] = getAddition
})
// now I don't know whats next, how do I update objectKeys to include the
// additions added in the forEach loop.
// What I really want is to not have to add the 'get' values to the object
// at all, JUST to the type. I want typechecking for the get values that
// may or may not actually exist on the object.
希望这就是clearerer和这样。
据我读的keyof和映射类型的规范,是没有办法做到这一点。希望我错了,但转换关键名称并不是我见过的打字稿团队演示的一个功能。 –