#`Literal type inference not working for object properties returned from generic function`

5 messages · Page 1 of 1 (latest)

quaint flare
#

I have a generic function createModel that accepts an options object with literal types, but the return type loses the literal type information.

interface ModelOptions extends Readonly<Record<string, any>> {
  resourceId: string;
  _relations?: Readonly<Record<string, ModelOptions>>;
}

const createModel = <const TModelOptions extends ModelOptions>(
  options: TModelOptions,
) => {
  return {
    resourceId: options.resourceId,
  };
};

const bojan = createModel({
  resourceId: 'bojan',
  _relations: {
    someKey: createModel({
      resourceId: 'Woop',
    }),
  },
});

// Wanted output:
// (property) resourceId: "bojan"
// Output I get:
// (property) resourceId: string
bojan.resourceId;
silk sonnet
#

if you hover over the return type of createModel you'll see that it's just { resourceId: string }, i.e. it's not related to the type parameter at all. you need an explicit return type annotation:

lilac joltBOT
#
mkantor#0

Preview:```ts
interface ModelOptions extends Readonly<Record<string, any>> {
resourceId: string;
_relations?: Readonly<Record<string, ModelOptions>>;
}

const createModel = <const TModelOptions extends ModelOptions>(
options: TModelOptions,
): Pick<TModelOptions, 'resourceId'> => {
...```

silk sonnet
quaint flare