Type-safe way to transform a key and a value into an object with that single key/value

前端 未结 1 1637
耶瑟儿~
耶瑟儿~ 2021-01-27 11:10

I want to write a function valueToObject that, given a key and a value, yields an object with that single key and value, e.g.:

valueToObject(\'myKe         


        
1条回答
  •  别那么骄傲
    2021-01-27 11:53

    When using a computed property the type with a generic parameter the type will be inferred to { [name: string]: V }. This seems to be related to this issue, which although is marked as fixed, you can see @jcalz commented about 4 days ago that this is still happening on 2.9.

    Edit This issue seems to be a close match and is still open with a target of 3.0 so we may get a fix soon

    The only work around is to use a type assertion:

    function valueToObject(key: K, value: V): Wrapped {
        return { [key]: value } as Wrapped;
    }
    //OR
    function valueToObject(key: K, value: V): Wrapped {
        var result = {} as   Wrapped
        result[key] = value;
        return result;
    }
    

    I suggest you report this on GitHub, or comment on the issue to draw attention to the fact that this still happens.

    0 讨论(0)
提交回复
热议问题