【问题标题】:How to define an object values as specific type?如何将对象值定义为特定类型?
【发布时间】:2019-02-13 11:56:00
【问题描述】:

想象一下你的打字稿函数接收一个对象作为参数。现在我想声明任何值都是string 类型。所以想法是将对象视为Map,但不绑定到它们的类型。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    试试这个代码:

    function f<T>(o: { [key: string]: T }) {
        console.log(o);
    }
    
    f<number>({a: 1, b: 3}) // ok
    f<string>({a: 'aa'}) // ok
    f<string>({a: 'aa', b: 132}) // error - Property 'b' is incompatible with index signature.
    

    更多详情 - 查看Index types and string index signatures上的文档

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2018-10-13
      • 2013-12-11
      • 1970-01-01
      • 2021-07-21
      • 2019-04-10
      • 2021-12-08
      相关资源
      最近更新 更多