Skip to content

Type guard - type propagation  #37339

Description

@senyaak

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

Activity

  1. MartinJohns commented on Mar 11, 2020

    @MartinJohns
    Contributor

    Most likely the same issue as #9998.

  2. RyanCavanaugh commented on Mar 11, 2020

    @RyanCavanaugh
    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.

  3. typescript-bot commented on Mar 14, 2020

    @typescript-bot
    Contributor

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

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions