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

Inconsistent narrowing of 'any' type #6301

Closed
tinganho opened this issue Dec 31, 2015 · 2 comments
Closed

Inconsistent narrowing of 'any' type #6301

tinganho opened this issue Dec 31, 2015 · 2 comments
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead Canonical This issue contains a lengthy and complete description of a particular problem, solution, or design

Comments

@tinganho
Copy link
Contributor

let value1 : string | any;
if (typeof value1 === 'string') {
    value1 // <-- check me
}

let value2: Object | any;
if (value2 instanceof Object) {
    value2 // <-- check me
}

function isString(value: string | any) : value is string {
    return typeof value === 'string';
}
let value3: string | any;
if (isString(value3)) {
    value3 // <-- check me
}

Only the typeof query will narrow to a non-any type above.

@DanielRosenwasser
Copy link
Member

I think any being in a union here is unrelated.

You don't want to narrow from any to Object because now you can effectively do nothing with your value. So in general, we don't narrow with instanceof type guards. See #1426 for why.

User-defined type guards need to exhibit the same behavior (because they might internally use an instanceof guard); however, we are considering narrowing from any for primitives, regardless of the type guard you use. See #5930 and #6015.

@DanielRosenwasser DanielRosenwasser added By Design Deprecated - use "Working as Intended" or "Design Limitation" instead Question An issue which isn't directly actionable in code Canonical This issue contains a lengthy and complete description of a particular problem, solution, or design and removed Question An issue which isn't directly actionable in code labels Dec 31, 2015
@DanielRosenwasser DanielRosenwasser changed the title Inconsistence narrowing of union consisting of any type Inconsistence narrowing of 'any' type Dec 31, 2015
@DanielRosenwasser DanielRosenwasser changed the title Inconsistence narrowing of 'any' type Inconsistent narrowing of 'any' type Dec 31, 2015
@tinganho
Copy link
Contributor Author

Ok thanks @DanielRosenwasser. I have followed the discussion about any narrowing. Didn't know the rule applied to union consisting of type anys too.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead Canonical This issue contains a lengthy and complete description of a particular problem, solution, or design
Projects
None yet
Development

No branches or pull requests

2 participants