From a4f5af3ea560b8029012f5e10be631aecc2286cc Mon Sep 17 00:00:00 2001 From: Jos de Jong Date: Thu, 14 Sep 2023 19:31:21 +0200 Subject: [PATCH] Defined the signature of the function that is being created too --- src/infer.ts | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/infer.ts b/src/infer.ts index e3aa2b6..9eb09aa 100644 --- a/src/infer.ts +++ b/src/infer.ts @@ -9,19 +9,19 @@ const create = createFactory<{ number: number bigint: bigint string: string - // T: T // TODO: how to do generics? - // 'Complex': unknown // TODO: how to do generics? + any: any }>() - -// TODO: how to pass config? -// These are the interfaces: +// These are our string based interfaces, which we can use both in typed-function and in TypeScript: const Multiply = 'multiply(number,number)=>number' +const Sqrt = 'sqrt(number)=>number' const Zero = 'zero(number)=>number' +// TODO: get generics working +// TODO: how to pass config? -const createSquare = create([Multiply, Zero],dep => { - return (x: number) => dep.multiply(x, x) -}) +const createSquare = create(Sqrt, [Multiply, Zero],dep => + x => dep.multiply(x, x) +) // the code works in JS, and works in TS const multiply = (a: number, b: number) => a * b @@ -43,15 +43,22 @@ function createFactory>() { ? [ResolveType] : never - type FunctionDefinition = + type DependencyRecord = FnType extends Value ? K extends `${infer Name}(${infer Args})=>${infer ReturnType extends BaseTypeNames}` ? Record) => ResolveType> : never : never + type CreatedFunctionType = + FnType extends Value + ? K extends `${infer Name}(${infer Args})=>${infer ReturnType extends BaseTypeNames}` + ? (...args: ResolveArguments) => ResolveType + : never + : never + // inspired by: https://stackoverflow.com/questions/68391632/infer-type-from-array-literal - type DepRecord< + type DependenciesRecord< Arr extends Array>, Result extends Record = {} > = Arr extends [] @@ -59,16 +66,17 @@ function createFactory>() { : Arr extends [infer H, ...infer Tail] ? Tail extends Array> ? H extends Value - ? DepRecord> + ? DependenciesRecord> : never : never : never - return function create[], W>( + return function create[], W extends Value>( + signature: W, dependencies: [...Dependencies], - callback: (deps: DepRecord<[...Dependencies]>) => W + callback: (deps: DependenciesRecord<[...Dependencies]>) => CreatedFunctionType ) { - console.log('Creating typed-function with dependencies:', dependencies) + console.log('Creating typed-function with', { signature, dependencies }) // TODO: create a typed-function for real return callback }