Skip to content

Type parameter inference of function chained parameters and return values does not work. #38872

Closed
@WearyMonkey

Description

@WearyMonkey

I'm writing an API with life cycle methods that are called in a specific order. Each life cycle method can return a 'state' object that is passed to the next life cycle method. I would like the API to be strongly typed, and the type of the state parameters to be inferenced from the return type of the previous life cycle method.

TypeScript Version: 3.9.2, 4.0.0-dev.20200530

Search Terms:

chain inference inference parameter

Code

type Chain<R1, R2> = {
  a(): R1,
  b(a: R1): R2;
  c(b: R2): void;
}

function test<R1, R2>(foo: Chain<R1, R2>) {

}

test({
  a: () => 0,
  b: (a) => 'a',
  c: (b) => {
    const x: string = b; // Type 'unknown' is not assignable to type 'string'.(2322)
  }
});

Expected behavior:

No error.

Actual behavior:

Error 2322 on const x: string = b

Removing the a parameter removes the error and works as expected, e.g.

// ...same as above...

test({
  a: () => 0,
  b: () => 'a',
  c: (b) => {
    const x: string = b; // no error
  }
});

Explicitly providing the parameter type also works, e.g.

// ...same as above...

test({
  a: () => 0,
  b: (a: number) => 'a',
  c: (b) => {
    const x: string = b; // no error
  }
});

Playground Link:

https://www.typescriptlang.org/play?#code/C4TwDgpgBAwgFgQwJYDsA8AlAjAGihgJgD4oBeKAbwCgooEAKASgC59caoAjehV7F-AQDcHAMb1OfAgIBuAeyQATEQF8qVAGYBXFKOBI5KKMAgBnYJlyCi9DXLmt4ydNjyEijSurVUT5+tS0vFBMZCQADDgckiEInqQkAOQIiVG0oqwS8SSBtFCihuZQAB6s5gBOqADmZFwitGoqjCJAA
Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixedFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions