Colin Han
Colin Han

Reputation: 41

How to define this type

I have a generic function defined like following:

function foo<T extends Record<string, unknown>>(arg1: string, arg2: string): Promise<T> {
  // Could get data from network
  return Promise.resolve({ arg1, arg2 } as any as T);
}

I want generate a series generic functions as belongs:

const foo1 = foo.bind(null, 'a');
const foo2 = foo.bind(null, 'b');
// ...

My Question is: How to add explicit type declaration for foo1, foo2, etc?

I try to add type declaration like following:

type B = <T extends Record<string, unknown>>(arg2: string) => Promise<T>;

const foo1: B = foo.bind(null, 'a');

It works in one typescript project, but in my new typescript project, it is not work. I got a build error like following:

TS2322: Type '(arg2: string) => Promise<Record<string, unknown>>' is not assignable to type 'B'.
  Type 'Promise<Record<string, unknown>>' is not assignable to type 'Promise<T>'.
    Type 'Record<string, unknown>' is not assignable to type 'T'.
      'Record<string, unknown>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record<string, unknown>'.

Thanks

Upvotes: 0

Views: 41

Answers (1)

Colin Han
Colin Han

Reputation: 41

Now I use following workaround for this problem.

const foo1 = foo.bind(null, 'a') as any as B;

Upvotes: 1

Related Questions