Function that creates a new object with properties set to the values of the input objects specific key in typescript

huangapple go评论43阅读模式
英文:

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&lt;TObjects extends namedObject[]&gt;(...namedObject: TObjects): {
    [key in TObjects[number][&#39;name&#39;]]: number
}

const a = createObjectWithKey({
    name: &#39;test&#39;
}, {
    name: &#39;test2&#39;
});

/** What I would want here, is that a be typed as an object that has a &quot;test&quot; and &quot;test2&quot; property, which values should be &quot;number&quot;, like this
 * 
 * type createdObjectType = {
 *     &#39;test&#39;: number,
 *     &#39;test2&#39;: 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&lt;TObjects extends readonly namedObject[]&gt;(namedObject: TObjects): {
    [key in TObjects[number][&#39;name&#39;]]: number
}

const a = createObjectWithKey([{
    name: &#39;test&#39;
}  , {
    name: &#39;test2&#39;
}] 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 &quot;test&quot;.

playground

huangapple
  • 本文由 发表于 2023年2月27日 17:38:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定