You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm not sure if this is related to or even a duplicate of #14957. I was attempting to define an unknown type similar to the one described in #10715, with a predicate for testing the object case that narrows the type to a dictionary type, and ran into this issue. I'm including a more minified test case below.
I could easily believe that this isn't a bug but some misunderstanding on my part -- my apologies if so. It doesn't seem like it should be a problem with subtyping; AFAICT {[key: string]: number} is a subtype of {}, right?
TypeScript Version: 2.2.2 with all strict checks turned on
Code
typeNumberDict={[key: string]: number};typeNullableObject={}|null;functionnullableObjectIsNumberDict(x: NullableObject): x is NumberDict{// bogus logic; the point of this example is just the typesreturn!!x;}functionuse(x: NullableObject){if(!nullableObjectIsNumberDict(x)){return;}x// I expected NumberDict; TS says {}}
Expected behavior:
The narrowed type of x should be NumberDict.
Actual behavior:
The narrowed type of x is {}.
The text was updated successfully, but these errors were encountered:
@dherman (Hi, Dave!) The issue you're running into here is that { } and { [key: string]: number } are both assignable to each other. The less obvious relation, that { } is assignable to { [key: string]: number }, technically should be true only when we know { } to exactly represent an empty object, but in practice that isn't feasible to track. Anyway, because { } is assignable to { [key: string]: number }, we take it to be a more specific type and therefore keep it following the type guard.
It works if you change your NullableObject declaration to
typeNullableObject=object|null;
The object primitive type was introduced in 2.2. See #1809 for more context.
I'm not sure if this is related to or even a duplicate of #14957. I was attempting to define an
unknown
type similar to the one described in #10715, with a predicate for testing the object case that narrows the type to a dictionary type, and ran into this issue. I'm including a more minified test case below.I could easily believe that this isn't a bug but some misunderstanding on my part -- my apologies if so. It doesn't seem like it should be a problem with subtyping; AFAICT
{[key: string]: number}
is a subtype of{}
, right?TypeScript Version: 2.2.2 with all strict checks turned on
Code
Expected behavior:
The narrowed type of
x
should beNumberDict
.Actual behavior:
The narrowed type of
x
is{}
.The text was updated successfully, but these errors were encountered: