Skip to content

Overwriting an unknown variable does not change the typeΒ #45098

Closed
@midgleyc

Description

@midgleyc

Bug Report

πŸ”Ž Search Terms

unknown, overwrite, replace

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about common bugs that aren't bugs

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

import {strict as assert} from 'assert';

async function overwrite(err: unknown) {
  err = 'hello';
  assert(err.startsWith('h'));
  // err is 'unknown' but should be 'string'
}

πŸ™ Actual behavior

Errors because err is type unknown.

πŸ™‚ Expected behavior

No error because err is a string by that point.

Motivating example

I am reading off .error from an Angular HttpErrorResponse object. error is any, and can be at least string, JSON or Blob. I set it to "unknown" for type safety.

async function dealWith(err: unknown) {
  if (err instanceof Blob) {
    const isJson = err.type.endsWith('json');
    err = await err.text();
    if (isJson) {
      err = JSON.parse(err);
    }
  }
  // code that checks whether err is string or JSON and deals with it
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions