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

Type guard - type propagation #37339

Closed
senyaak opened this issue Mar 11, 2020 · 3 comments · Fixed by #56908
Closed

Type guard - type propagation #37339

senyaak opened this issue Mar 11, 2020 · 3 comments · Fixed by #56908
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@senyaak
Copy link

senyaak commented Mar 11, 2020

If I use variable which has type set via type guard in nested anonymous class - it becomes of type any.
TypeScript Version: 3.8.3

Search Terms: Type guard, type propagation

Code

function isError(error: Error | any): error is Error {
  return error instanceof Error;
}

try {
    throw new Error('test');
} catch(hookError) {
    if(isError(hookError)) {
    
        const errorHandler = class extends Error {
    
            log() {
                // hookError is any
                console.log(hookError.message);
            }
        };
    } else {
        throw hookError;
    }
}

Expected behavior: hookError in console.log should have type Error

Actual behavior: hookError has type any

Playground Link: http://www.typescriptlang.org/play/?ssl=21&ssc=1&pln=1&pc=1#code/GYVwdgxgLglg9mABDAzgUQE4bhgFAUyxwC5FNsNEAfRAQzAE8BKUwi5FMoygbwChEiDPiggMSNjmRgUUehHxxgXCgG4+AXz58oGBon6DBUABbYA7ojD5L5HLgDkUfLIdN1GxBFpQIJ3CZwcADWdhhMBgJGMMC4qGEBQaHcTBGGRlFGRhAIsoiSGAAS9AAmADaEiAC8XmW0KJz4AB7OYCWcYZFZmVm9ZXAA5rhpPb1jiAD0E4iBIZ2odIyj41k5MnAVAHT9Q7PJFJsAti4otAP47stjWisa6lme+GUo+F3jphYzSWH3RlpaQA

Related Issues: I think this #30557 could be same issue, but not sure

@MartinJohns
Copy link
Contributor

Most likely the same issue as #9998.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Mar 11, 2020
@RyanCavanaugh
Copy link
Member

In addition to #9998, hookError has type any, and anys don't get narrowed by type guards. See other issues on annotated catch clause variables.

@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants