Anders
Anders

Reputation: 17554

Typescript generic arguments not resolved correclty

consider this, a generic class

export class Query<TResult> {
}

A extending class of that type

export class ListSomeNumbersQuery extends Query<number[]> {
    constructor() {
        super();           
    }
}

A visitor class

class CqsClient {
    executeQuery<TResult>(query: Query<TResult>): TResult {
        //TODO: implement
    }
}

usage

var result = client.executeQuery(new ListSomeNumbersQuery());

Visual Studio IDE does not understand that result is a number array. Whats wrong?

edit: Really funny choice by Anders Hejlsberg, Typescript is a type erasure language so generics are only compile time syntax sugar. But adding a private property does work

export class Query<TResult> {
    private _dummy: TResult;
}

Upvotes: 2

Views: 67

Answers (1)

Daniel
Daniel

Reputation: 11162

It happens because you don't use your type variable TResult in your Query class.

From Docs:

When inferring the type of T in the function call, we try to find members of type T on the x argument to figure out what T should be. Because there are no members which use T, there is nothing to infer from, so we return {}.

If you change it to

export class Query<TResult> {
  private result: TResult;
}

it will correctly identify the result as a number[] instead of {}

Upvotes: 1

Related Questions