Cailen
Cailen

Reputation: 690

Typescript compiler generating wrong return type for Reselect.createSelector()

As far as I can tell the .d.ts file for reselect (https://github.com/reactjs/reselect) is correct. So what's going on here... is it a problem with the Typescript compiler? My tsconfig?

To reproduce the issue:

Demo.ts

import { createSelector, Selector } from 'reselect';

export interface DemoState {
    values: {
        value1: number,
        value2: number
    },
}

export const selectTotal = createSelector<DemoState, number, number, number>(
    state => state.values.value1,
    state => state.values.value2,
    (value1, value2) => {
        return value1 + value2;
    }
);

From the reselect.d.ts it appears that createSelector() above should return type Selector<DemoState, number>:

reselect.d.ts

function createSelector<TInput, TOutput, T1, T2>(selector1: Selector<TInput, T1>, selector2: Selector<TInput, T2>, combiner: (arg1: T1, arg2: T2) => TOutput): Selector<TInput, TOutput>;

type Selector<TInput, TOutput> = (state: TInput, props?: any) => TOutput;

However, what the typescript compiler is actual generating for a definition is:

Demo.d.ts

export declare const selectTotal: Selector<DemoState, number, number, number>;

Soo... when I go to import selectTotal in another project I get the error: "Generic type 'Selector' requires 2 type argument(s)." Because reselect.d.ts only defines Selector<TInput, TOutput> and, as far as I can tell, that's what createSelectorshould be returning, regardless of the number of type arguments passed in to it.

The only way I can get the correct definition generated is by explicitly casting the createSelector result, but I don't think I should be having to do this..

export const selectTotal = createSelector<DemoState, number, number, number>(
state => state.values.value1,
state => state.values.value2,
(value1, value2) => {
    return value1 + value2;
}) as Selector<DemoState, number>;

Using TypeScript 2.0.3, and my tsconfig in case it's relevant:

{
  "compileOnSave": true,
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist",
    "declaration": true,
    "sourceMap": true,
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "jsx": "preserve",
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "removeComments": false,
    "preserveConstEnums": true
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

Upvotes: 1

Views: 1646

Answers (1)

Cailen
Cailen

Reputation: 690

Turns out this was an issue with the TypeScript 2.0.3 compiler. Upgrading to 2.0.6+ resolves the issue.

https://github.com/Microsoft/TypeScript/issues/12370

Upvotes: 2

Related Questions