【问题标题】:what is the typescript signature of function makeObject(key,value){ return {[key]:value}; }?什么是函数 makeObject(key,value){ return {[key]:value} 的打字稿签名; }?
【发布时间】:2020-07-19 20:16:15
【问题描述】:
//fake code;there shoud be type annotations
function makeObject(key,value){ 
   return {[key]:value}; 
}
const obj=makeObject("name","Tom");

我想要什么

我希望 typescript 编译器推断 obj 的类型为 {"name":string},但我不知道 "makeObject" 的签名应该是什么。

我尝试过的

我已经弄清楚如何让 tsc 将“名称识别为字符串文字类型”。

function makeKey<Key extends keyof {[k:string]:any}>(key:Key):Key{
    return key;
}
const key=makeKey("name")//tsc infer "key" has type "name" not string

我的问题

当前的 typescirpt(3.9+) 可以做到这一点吗?如果是那怎么办? 提前致谢!

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您在键类型K 和值类型V 中创建函数generic,其中K 被限制为PropertyKey(基本上是stringnumbersymbol )。

    唯一的障碍是由于microsoft/TypeScript#13948,编译器会将{ [key]: value } 视为具有index signature 的类型。这可能不是您想要的...您不是试图将V 类型的值放在所有可能的键上,而只是K 类型的一个。

    我们可以通过asserting 解决这个问题,它属于mapped type {[P in K]: V},相当于Record&lt;K, V&gt;,意思是“一个对象的键类型为K,值类型为V”:

    function makeObject<K extends PropertyKey, V>(key: K, value: V) {
       return { [key]: value } as { [P in K]: V };
    }
    const obj = makeObject("name", "Tom"); // {name: string}
    

    看起来像你想要的。希望有帮助;祝你好运!

    Playground link to code

    【讨论】:

    • 这正是我想要的。我不知道有一个内置的“PropertyKey”,非常感谢。
    • 不客气;如果满足您的需求,请考虑接受答案!
    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 2015-07-22
    • 2012-04-18
    • 2013-06-24
    • 2016-01-11
    • 2013-03-23
    • 2015-10-12
    • 1970-01-01
    相关资源
    最近更新 更多