请看下面的代码:
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
* }
*/
我怎样写函数的签名,使返回类型是我想要的对象?
连接至Playground
1条答案
按热度按时间8xiog9wr1#
我通过稍微改变函数并添加
as const
使其工作。它的工作原理是,当你给予
as const
时,TS把整个数组当作一个不可变的东西,它知道这个名字不会是任何随机的字符串,它只会是这些特定的字符串,也就是说,typeof namedObject[0].name
不是string
,它是"test"
。运动场