Closed
Labels
Breaking ChangeWould introduce errors in existing code
Milestone
Description
This is a place holder for changes to the type narrowing behavior in TypeScript 2.0:
- Generic type parameters are now narrowed
function g<T>(obj: T) {
var t: T;
if (obj instanceof RegExp) {
t = obj; // RegExp is not assignable to T
}
}See the explanation by Arnav Singh (@Arnavion) in #7719 (comment)
- Type narrowing does not work for catprued variables in functions and class expressions
export class Class {
constructor(public p) { }
}
var c: Class | string;
var x: Class;
if (c instanceof Class) {
function inner() {
x = c; // Error, type of c is not narrowed, c is Class | string
}
x = c; // OK, c is Class
}Metadata
Metadata
Assignees
Labels
Breaking ChangeWould introduce errors in existing code
Activity
ivogabe commentedon Mar 24, 2016
In the first example
objshould be narrowed toT & RegExp, that seems more correct. Is that doable?mhegazy commentedon Mar 24, 2016
narrowing makes the type more "specific", this seems like expanding the domain of the type.
ivogabe commentedon Mar 24, 2016
I thought that "more specific than" means "subtype of". That would mean that narrowed types are always a subtype of their original type and also always assignable to the original type.
RegExpis not a subtype of all possible types forT, since it is a type argument, butT & RegExpis a subtype of it. Or is there something that I missed?mhegazy commentedon May 13, 2016
Type parameter narrowing is tracked by #8563
Strate commentedon Jun 10, 2016
Can typescript track that variable isn't changed after bypassing to callback and keep that narrow inside callback?
i.e:
mhegazy commentedon Jun 10, 2016
it can be done, but that is not trivial amount of computing, and would impact compilation times for all projects.
Arnavion commentedon Jun 10, 2016
Artur Eshenbrener (@Strate) In that case you can yourself use
constinstead ofletand get that behavior.