【问题标题】:Define the type of an object with string keys and function values用字符串键和函数值定义对象的类型
【发布时间】:2020-02-02 20:11:16
【问题描述】:

我有一个带有一个参数的节点 JS 函数,该参数是一个带有键的对象,而值是函数,然后解析为基础值。

我们刚刚切换到 TS,我不知道如何定义参数的 key:value 类型,更不知道如何将 function 定义为值类型?

TS函数长这样……

const myJSFunction = o => input => ...

其中ostring:function 对象。然后将input 传递给o 的每个函数values

所以我在想有一些类似的签名......

// define the generic <R> function as <U => any>
// define the generic <T> as an object of { string : R }
const myTSFunction = (o: T) => (input: U) => ...

还是什么?我在这里抓住了稻草,因为我对 Typescript 的了解还不够,无法知道泛型的可能性。

谢谢

【问题讨论】:

    标签: node.js typescript generics functional-programming


    【解决方案1】:

    这样的事情怎么样:

    // We define what the type o is
    // key: string means "any key should ..."
    interface Obj<T> {
      [key: string]: (input: T) => void,
    };
    
    // We instantiate an object for the test
    const o: Obj<string> = {
      a: (input) => { },
      b: (input) => { },
    };
    
    // We define the function to work with any type of value of obj
    // and call it for the test
    function myTSFunction<T>(obj: Obj<T>, val: T): void {
      obj[0](val);
    }
    

    【讨论】:

    • 哦...这看起来很有希望。我试试看,谢谢。
    • 最后我找到了一种稍微不同的方法,但这很有帮助。谢谢!我投了赞成票,最后我会发布我得到的解决方案。
    【解决方案2】:

    Grégory NEUT 的回答很有帮助,但我在途中发现了一些其他限制(JS 一直躲起来)。我使用的是 Lodash,所以我的对象不仅仅是一个对象,而是他们定义的类型。

    所以我定义了一些新类型...

    type TransformerFunction<T> = (o: T) => any;
    type TransformerObject<T> = Dictionary<TransformerFunction<T>>;
    

    然后函数就变成了……

    export const objectTransform = <T extends any>(o: TransformerObject<T>) => <U extends T>(json: U): Dictionary<any> => _.flow(
      _.mapValues((f: TransformerFunction<T>) => f(json)),
      _.omitBy(_.isUndefined),
      _.omit('undefined'),
    )(o);
    

    这就是我在 JS 中转换 JSON 并现在将其转移到 TS 并喜欢泛型的方式。

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 2018-12-12
      • 2021-02-28
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多