0

I have this kind of code:

type MapOf<V> = { [key: string]: V };

type ThingWithConfigCallback<ThingType, ConfigType extends MapOf<any>> = (
  Thing: ThingType,
  config?: ConfigType,
) => void;

type ThingWithConfig<ThingType, ConfigType extends MapOf<any>> = {
  Thing: ThingType,
  config?: ConfigType,
};

const createThingsWithConfig <T, C>() => {
  const registerThingsWithConfig: ThingWithConfigCallback<T, C> = (Thing: T, config: C) => {
  // do stuff to register things
  }
  // other functions
  return {
    registerThingsWithConfig,
    // other functions
  }
};

However I want to provide a default parameter for config for registerThingsWithConfig, instead of leaving it undefined. However I can't create a default that's of the correct type/subtype.

If I do (Thing: T, config: C = {}) => { I get Type '{}' is not assignable to C and how Type '{}' is assignable to the constraint of 'C', but 'C' could be instantiated with a different subtype of constraint 'MapOf<any>'

If I declare const defaultConfig: MapOf<any> = {}; and use that as the default param in registerThingsWithConfig I get the same error but with Type MapOf<any> is assignable to the constraint of 'C' ...

But I do not follow how/why that is the case, even after reading How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"? .

AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
  • 1
    Personally I would use an `as` assertion. I don't think there's any way around it. – Linda Paiste Jan 11 '23 at 18:20
  • 1
    It's an error because you don't know for sure what `C` is, and `C` could *theoretically* have some required properties and therefore `{}` would not be assignable to that `C`. Example: `const x = createThingsWithConfig(); x.registerThingsWithConfig('text');`. – Linda Paiste Jan 11 '23 at 18:27
  • @LindaPaiste your examples is amazingly clear to me. Thank you. Please do put that in an answer so I can upvote it and mark it as correct – AncientSwordRage Jan 12 '23 at 01:49

0 Answers0