Sasha
Sasha

Reputation: 5944

Generic function type is not applied to the returned object members

I'm defining a function which returns an object which members are functions with the same payload. Payload type is defined through generic, which extends object. However, flow complains that generic type is different then passed:

export const getObj = <T: {}>(url: string) => ({
  create: (entity: T) => console.log(url, entity),
  ...
});

const url = '/some-path';

type TEntity = {
  some: string,
};

const entity: TEntity = {
  some: 'value',
};

const instance = getObj<TEntity>(url);

instance.create(entity);

Flow complains:

^ Cannot call instance.create with entity bound to entity because TEntity 2 is incompatible with T 2.

Try.

What I'm doing wrong?

Upvotes: 1

Views: 56

Answers (1)

Lyle Underwood
Lyle Underwood

Reputation: 1304

When in doubt, be more explicit.

// @flow

type EntityFactory<T> = $ReadOnly<{|
  create: (T) => void,
|}>;

export const getObj = <T>(url: string): EntityFactory<T> => ({
  create: (entity: T) => console.log(url, entity),
});

const url = '/some-path';

type TEntity = {
  some: string,
};

const entity: TEntity = {
  some: 'value',
};

const instance = getObj<TEntity>(url);

instance.create(entity);

Upvotes: 1

Related Questions