Home > Enterprise >  Function return type based on the elements of array passed as an argument
Function return type based on the elements of array passed as an argument

Time:04-17

I'm trying to find a way to create function which return type depends on the elements of array passed as an argument

const arr1 = ['a', 'b'] as const
const arr2 = ['a', 'c'] as const

func(arr1)     // return type {a: any, b: any}
func(arr1).a   // ok
func(arr1).b   // ok
func(arr1).c   // TYPE ERROR

func(arr2)     // return type {a: any, c: any}
func(arr2).a   // ok
func(arr2).b   // TYPE ERROR
func(arr2).c   // ok

So something like that but actually working

function func<T>(array: T): {[K in typeof array[number]]: any}

CodePudding user response:

So close!

function func<A extends ReadonlyArray<string>>(array: A): { [K in A[number]]: any } { ... }

A[number] will give us a union of all the strings inside it, and then we can map over that.

You can think of the generic here as a "retaining" the type of array over to the return type so we can use it.

Playground

  • Related