Skip to content

Generic argument type inference regression in TS 3.4 #30074

Closed
@ulrichb

Description

@ulrichb

TypeScript Version: 3.4.0-dev.20190223

Search Terms: 3.4 inference generic readonly

Code

The following snippet emits an error in TS 3.4 whereas in TS 3.3 it compiles fine.

class ErrorResult {
    readonly isError = true;

    static combine(errorResults: ReadonlyArray<ErrorResult>): ErrorResult {
        return new ErrorResult(/* ... combine errorResults ... */);
    }
}

//

function extractAndCombineErrorResults<T, TErrorResult extends ErrorResult>(
    allResults: ReadonlyArray<T | TErrorResult>,
    combine: (details: ReadonlyArray<TErrorResult>) => TErrorResult,
): ReadonlyArray<T> | TErrorResult {

    return /* dummy result: */ [];
}

//

interface SomeResult {
    isSomeResult: true
}

const allResults: ReadonlyArray<SomeResult | ErrorResult> = [];

// Here the inference doesn't work anymore:
const result1: ReadonlyArray<SomeResult> | ErrorResult =
    extractAndCombineErrorResults(allResults, ErrorResult.combine);

// Explicit generic args work:
const result2: ReadonlyArray<SomeResult> | ErrorResult =
    extractAndCombineErrorResults<SomeResult, ErrorResult>(
        allResults, ErrorResult.combine);

Command line: npx tsc TypeScriptIssue.ts

Expected behavior:
No compile error.

Actual behavior:

TSC emits

TypeScriptIssue30074.ts:28:7 - error TS2322: Type 'ErrorResult | readonly (ErrorResult | SomeResult)[]' is not assignable to type 'ErrorResult | readonly SomeResult[]'.
  Type 'readonly (ErrorResult | SomeResult)[]' is not assignable to type 'ErrorResult | readonly SomeResult[]'.
    Type 'readonly (ErrorResult | SomeResult)[]' is not assignable to type 'readonly SomeResult[]'.
      Type 'ErrorResult | SomeResult' is not assignable to type 'SomeResult'.
        Property 'isSomeResult' is missing in type 'ErrorResult' but required in type 'SomeResult'.

28 const result1: ReadonlyArray<SomeResult> | ErrorResult =
         ~~~~~~~

Playground Link: (works in TS 3.3)

Possibly related: #29435

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions