Anarion
Anarion

Reputation: 2534

Typescript - faulty type checking for generic functions returning Promise

When a generic fucntion returns Promise<T> typescripts type-checking is failing. Am I doing somethig wrong, and is there a way to enforce typechecks in such a situation?

//Generic function
function get<T>(): Promise<T> ...

//Typed instance of function, should fail at compile-time Because T != T[]
const typedGet: <T = SomeClass>() => Promise<T[]> = get;

//Should also fail, because T != IterableIterator<T>
const typedGet2: <T = SomeClass>() => Promise<IterableIterator<T>> = get;

Upvotes: 1

Views: 61

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

Given the structural nature of the Typescript type system, and the fact that types are erased at compile time, I don't think it is necessarily faulty.

Let's examine the first case, renaming the type parameter for the signature to make things more clear.

const typedGet: <O = SomeClass>(n: O) => Promise<O[]> = get;

get is generic, and returns a Promise<T> and is being assigned to a function that returns Promise<O[]>, since there are no other constraints T can be O[]. Typescript will not try to match the individual type parameters of the function so O != T is not a problem.

If we were to add a parameter, the discussion would be different:

declare function get<T>(p: T): Promise<T> 
const typedGet: <O = SomeClass>(p: O) => Promise<O[]> = get;

Now if we try to match return types, T must be O[], but if we match parameter types T must be O so we can't reconcile this, and we get an error.

Upvotes: 1

Related Questions