Is it possible for the code below to be typed correctly?
JavaScript
x
12
12
1
function arrayElementTypes(array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) {
2
/// .. do something
3
/// .. and then return an array with each functions result
4
return array.map(arg => arg())
5
}
6
7
const [varA, varB, varC] = arrayElementTypes( () => "", () => ({prop: "prop"}), () => [1,2,3] )
8
// how can this be typed appropriately so that the :
9
// varA: string
10
// varB: {prop: string}
11
// varC: number[]
12
Advertisement
Answer
Managed to do it with
JavaScript
1
13
13
1
type ReturnTypes<T extends Array<(a: any[]) => any>> = {
2
[P in keyof T]: T[P] extends (a: any[]) => infer R ? R : never
3
}
4
5
type CustomArrayElement = (() => string) | (() => number) | (() => {prop: string}) | (() => number[])
6
7
function arrayElementTypes<T extends CustomArrayElement[]>(array: T): ReturnTypes<typeof array> {
8
return array.map(arg => arg())
9
}
10
11
const [varA, varB, varC] = arrayElementTypes( () => "", () => ({prop: "prop"}), () => [1,2,3] )
12
13
Thank you all for your help!!