英文:
Function that creates a new object with properties set to the values of the input objects specific key in typescript
问题
以下是您要翻译的代码部分:
type namedObject = {
name: string
}
declare function createObjectWithKey<TObjects extends namedObject[]>(...namedObject: TObjects): {
[key in TObjects[number]['name']]: number
}
const a = createObjectWithKey({
name: 'test'
}, {
name: 'test2'
});
请注意,函数签名的部分没有中文内容,因此不需要翻译。
英文:
Consider the following code:
type namedObject = {
name: string
}
declare function createObjectWithKey<TObjects extends namedObject[]>(...namedObject: TObjects): {
[key in TObjects[number]['name']]: number
}
const a = createObjectWithKey({
name: 'test'
}, {
name: 'test2'
});
/** What I would want here, is that a be typed as an object that has a "test" and "test2" property, which values should be "number", like this
*
* type createdObjectType = {
* 'test': number,
* 'test2': number
* }
*/
How could I write the functions signature, so that the return type is an object which I want?
Link to playground
答案1
得分: 2
我通过轻微更改您的函数并添加as const
使其工作。
type namedObject = {
name: string
}
declare function createObjectWithKey<TObjects extends readonly namedObject[]>(namedObject: TObjects): {
[key in TObjects[number]['name']]: number
}
const a = createObjectWithKey([{
name: 'test'
} , {
name: 'test2'
}] as const);
它之所以有效,是因为在使用as const
时,TS将整个数组视为不可变的对象。它知道名称不会是任意随机字符串,而只会是这些特定的字符串。也就是说,typeof namedObject[0].name
不是string
,而是"test"
。
英文:
I made it work by slightly changing your function and adding as const
.
type namedObject = {
name: string
}
declare function createObjectWithKey<TObjects extends readonly namedObject[]>(namedObject: TObjects): {
[key in TObjects[number]['name']]: number
}
const a = createObjectWithKey([{
name: 'test'
} , {
name: 'test2'
}] as const);
It works because when you give as const
, TS treats the whole array as an immutable thing. It knows that the name will not be any random string, it will only be these specific strings. That is, typeof namedObject[0].name
is not string
, it's "test"
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论