How can I get strongly-typed higher order functions in Typescript?

55 Views Asked by At

See the below code block:

interface TestHiveInput {
  input: string;
}

interface TestHiveOutput {
  output: string;
}

type ListenFunction = (value: any) => void;

type Hive<T, K> = (initialValue: T) => {
  set: (newValue: T) => void;
  listen: (listenFunction: ListenFunction) => void;
};

type HiveFunction<T, K> = (input: T) => K;

type GetHive<T, K> = (hiveFn: HiveFunction<T, K>) => Hive<T, K>;

const hive: GetHive<any, any> = (hiveFn: (input: any) => any) => {
  return (initialInput: any) => {
    let _value = hiveFn(initialInput);
    const _listeners: Array<ListenFunction> = [];

    return {
      set: (value: any) => {
        _value = value;
        _listeners.forEach(listener => {
          listener(hiveFn(_value));
        });
      },
      listen: (listenFunction: ListenFunction) => {
        _listeners.push(listenFunction);
        listenFunction(hiveFn(initialInput));
      },
    };
  };
};

const myHive: Hive<TestHiveInput, TestHiveOutput> = hive(input => {
  return {output: input.input + input.input};
});

In defining the function hive, I had to give it the type GetHive<any,any> in order for the code to compile.

But, I'd like to have its input and output type inferred from testHive, which has its input and output passed (TestHiveInput and TestHiveOutput) to the Hive type.

In other words, I'd like automatic type completion on the function arguments I pass when calling the hive function. Id like to be able to write:

const testHive: Hive<TestHiveInput, TestHiveOutput> = hive(input => { return {output: input.input + input.input}; });

And have my IDE know the function hive expects a function as an argument with TestHiveInput as an argument, and which returns TestHiveOutput.

Thank you in advance

I am trying to write higher order function in Typescript which infers its types for the previously defined function type.

0

There are 0 best solutions below