GeezerVison is showing github.com — Constrained types is not assignable to constrainer union types, and failed to narrow its type · Issue #8563 · microsoft/TypeScript
Constrained types is not assignable to constrainer union types, and failed to narrow its type #8563
Description
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'.
Activity
ahejlsberg commented on May 11, 2016
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.
DanielRosenwasser commented on May 13, 2016
sandersn commented on May 13, 2016
Yeah, it did basically what Anders Hejlsberg (@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 commented on May 13, 2016
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 commented on May 3, 2017
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.
Metadata
Metadata
Development
No branches or pull requestsIssue actions