I just made a complex function that take 3 arguments : name, types and method. This function stores a method in a store. It uses intellisense to infer the return type of the third agument from the second one.
addMethod.d.ts
interface SimplifiedTypeMap {
string: string;
number: number;
boolean: boolean;
}
type GlobalMethodAdd = <T extends keyof SimplifiedTypeMap>(
name: string,
types: T[],
method: () => SimplifiedTypeMap[T]
) => void;
interface MethodStore {
[name: string]: {
types: (keyof SimplifiedTypeMap)[];
method: () => SimplifiedTypeMap[keyof SimplifiedTypeMap];
};
}
Thanks to intellisense, the return type of the last argument (method) is inferred from the items in the second argument (types) and int forces the user of the function to write a method with a specific return type
addMethod.ts
import { random } from "lodash-es";
export const methodStorage: MethodStore = {};
const addMethod: GlobalMethodAdd = (name, types, method) => {
methodStorage[name] = { types, method };
};
addMethod("test", ["string", "number"], () =>
random(1, true) > 0.5 ? "abcd" : 1234
);
When i'm using the addMethod function on Visual-Studio Code or Codesandbox, the return type of the third argument is well known but not on monaco-editor :