I'm trying to apply a default value to a generic. But whenever the generic is not provided, the generic is defaulting to the value given to an argument. I want to prevent this from happening. Here's a very simple example:
type Data = Record<string, any>
const computeData = <D extends Data = {}>(input: D): D => {
// Does some stuff to input
return input;
}
const res = computeData<{ name: string }>({ name: 'john' })
In this case the type of "res" is { name: string } as expected. But if the generic is not provided, I need it to default to {} which is the type given as the default value for the generic.
const computeData = <D extends Data = {}>(input: D): D => {
// Does some stuff to input
return input;
}
const res = computeData({ name: 'john' })
I have simplified the code for this example. I know in the context of this example this is kind of pointless.
EDIT: The actual use case is a network mocker that lets users add objects to mock graphql requests. I want to give them the option to provide resolver types. However, if they do not provide the types they are inferred from initial data passed in - I want to avoid this.
Type error because the initial call to constructor infers type for generic

This works because an explicit type is given when instantiating the class


{name: string}for both of them: typescriptlang.org/play?#code/…