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