#Function with return type depending on argument with default value

9 messages · Page 1 of 1 (latest)

tiny oak
#

How could I realize a function that

  • takes an array as argument
  • the return type is dependent on the array, for example just returning the same array again
  • the argument has a default value

I tried doing this, but am failing at the theoretical possibility of the user specifying a generics argument for the function but not the optional parameter

'[1, 2, 3]' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'any[]'

craggy kernelBOT
#
leumasme#0

Preview:```ts
function getArr<T extends any[]>(
arr: T = [1, 2, 3] as const
): T {
// ...
throw new Error("Not Implemented")
}

// Expected type: [1,2,3]
let a = getArr()
// Expected type: ["a","b","c"]
let b = getArr(["a", "b", "c"] as const)```

glad tulip
#

you kinda can't

#

uh i would like to retract my statement it is badly phrased

#

you can't with optional/defaulted parameter as the signature

#

because what if you call getArr<string[]>()? that's going to return [1, 2, 3] but says it returns string[]

#

so you would have to split it with overloads or just split the functions entirely

tiny oak
#

Hmm yeah that was what I suspected, just wanted to see if someone here knew about some magic that I didn't ^^ Thanks though!

#

!resolved