Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constrained types is not assignable to constrainer union types, and failed to narrow its type #8563

Closed
falsandtru opened this issue May 11, 2016 · 5 comments
Labels
Suggestion An idea for TypeScript

Comments

@falsandtru
Copy link
Contributor

TypeScript Version:

master

Code

function f<T extends string[] | {}>(a: T) {
  if (a instanceof Array) {
    a = a;
  }
}

Expected behavior:

$ node built/local/tsc.js index.ts

Actual behavior:

$ node built/local/tsc.js index.ts
index.ts(3,5): error TS2322: Type 'any[]' is not assignable to type 'T'.
@ahejlsberg
Copy link
Member

Hmm. This one is tricky. Currently the only type we consider assignable to a type parameter is that same type parameter (and any of course). In order for the above to work we would basically need to create a new type parameter that is a subtype of T and has a narrowed constraint string[]. It's possible, but it isn't a simple fix.

@ahejlsberg ahejlsberg added the Suggestion An idea for TypeScript label May 11, 2016
@DanielRosenwasser
Copy link
Member

I would think that #7422 would have allowed this. Care to weigh in @sandersn?

@sandersn
Copy link
Member

Yeah, it did basically what @ahejlsberg said -- but (1) only locally, when getting the narrowed type, and (2) not updated for control-flow rewrite of narrowing. So it can't be used as-is.

@ahejlsberg
Copy link
Member

I don't think the solution in #7422 works. The thing that makes this issue complicated is that you can't just clone type parameters without also being prepared to treat the clones as aliases for the original type parameter in the type instantiation logic. Otherwise you'll "leak" type parameters.

@ahejlsberg
Copy link
Member

This has worked correctly for a while now. The type guard produces type T & any[] which is assignable to T so there is no error. I'm closing this issue.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants