score:0

Accepted answer

it's not weird at all - in given syntax (function loaddata<t, u = tresponse<t>>() {...}) the u type can be "anything" - so it's not possible for typescript to know what may it be during the runtime as only u sub-types are assignable to it, and the { type: 'error', error: 'error message'} is not a sub-type of u

it won't get any better if you will change the definition to function loaddata<t, u extends tresponse<t> = tresponse<t>>() {...}, because situation is the same, the u type just got narrower though

in situation like this one you can't use generics for internal values (so the correct definition would be just function loaddata<t>() {...}), unless you somehow get the u type from somewhere, eg.

function loaddata<t, u = tresponse<t>>(loader: () => u) {
  const [data, setdata] = usestate<u | null>(null)

  setdata(loader());
}

loaddata<number>(() => ({ type: 'error', error: 'it works, lol' }))

Related Query

More Query from same tag