How to make this work? I want to constrain the generic type parameter but also have a default value of an empty object to data.
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
14 messages · Page 1 of 1 (latest)
How to make this work? I want to constrain the generic type parameter but also have a default value of an empty object to data.
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@ember stump Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:ts // // A constrained generic type parameter with default data. // function f<Data extends Record<any, any> = {}>( data: Data = {} ) { return data }
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?
Preview:ts // // A constrained generic type parameter with default data. // function f<Data extends Record<any, any>>( data: Data = {} as Data ) { return data }
!ts
//
// A constrained generic type parameter with default data.
//
function f<Data extends Record<any, any>>(data: Data = {} as Data) {
return data;
}
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
Yeah, I also considered using type assertions.
Also found this earlier: https://github.com/microsoft/TypeScript/issues/49158
i think that overloads are the only way to get the types to work out the way you want:
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 ?? {} }