此函数用于创建一个新对象,其属性设置为typescript中输入对象特定键的值

egmofgnx  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(110)

请看下面的代码:

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

8xiog9wr

8xiog9wr1#

我通过稍微改变函数并添加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"
运动场

相关问题