Home > Blockchain >  Typescript: Two functions take same parameters but have different return types
Typescript: Two functions take same parameters but have different return types

Time:02-20

I have the following types defined:

type MyType = <T>(a: string, b: Record<string, MyFunction<T>>) => T
type MyFunction<T> = () => T

I want to create another type (MyType2) that takes the same parameters but returns void.

I don't wish to use the same type for both and have it return T | void because one function must return T and one must return void.

How can I achieve this with Typescript in a DRY way?

I'm convinced it's possible but I cannot figure it.

CodePudding user response:

You can reuse the parameter types in a function using the Parameters helper and spread syntax:

type MyType2 = (...args: Parameters<MyType>) => void

Note that this results in a function type with an unknown instead of a generic function type with a type parameter:

(a: string, b: Record<string, MyFunction<unknown>>) => void

In this specific case that may not matter; I am not sure if there is a general way to do this which would output another generic function type with its own type parameter, but I suspect there is not, since Typescript does not support higher-kinded types. However, there is a way to make both functions generic without repeating too much code, by defining the parameters seperately as a generic tuple type:

type MyParameters<T> = [a: string, b: Record<string, MyFunction<T>>]

type MyType = <T>(...args: MyParameters<T>) => T
type MyType2 = <T>(...args: MyParameters<T>) => void

Playground Link

  • Related