#Constrained generic type parameter with default value

14 messages · Page 1 of 1 (latest)

ember stump
#
stark summitBOT
#

@ember stump Here's a shortened URL of your playground link! You can remove the full link from your message.

Fernando-Basso#5803

Preview:ts // // A constrained generic type parameter with default data. // function f<Data extends Record<any, any> = {}>( data: Data = {} ) { return data }

ember stump
#

One solution seems to do this:

function f<Data extends Record<any, any> = {}>(
  data: Data | {} = {}
) {
  return data;
}

But maybe the are other, more appropriate ways?

stark summitBOT
#
Ascor8522#7606

Preview:ts // // A constrained generic type parameter with default data. // function f<Data extends Record<any, any>>( data: Data = {} as Data ) { return data }

sharp ibex
#

!ts

stark summitBOT
#
//
// A constrained generic type parameter with default data.
//
function f<Data extends Record<any, any>>(data: Data = {} as Data) {
  return data;
}
sharp ibex
#

but that solution isn't perfacet either, since the consumer can provide a generic and no value

#

and there is very likely the default value doesn't match the generic

#

there is a snippet about that iirc

ember stump
river sparrow
#

i think that overloads are the only way to get the types to work out the way you want:

stark summitBOT
#
mkantor#7432

Preview:ts ... function f(): {} function f<Data extends Record<any, any>>( data: Data ): Data function f<Data extends Record<any, any>>( data?: Data ) { return data ?? {} }

river sparrow
#

but you have to be super careful in the implementation to uphold the promise of that second overload signature (basically you have to return data unchanged unless it's undefined)

#

TS won't check that for you