Skip to content

Overwriting an unknown variable does not change the type #45098

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

Closed
midgleyc opened this issue Jul 19, 2021 · 3 comments
Closed

Overwriting an unknown variable does not change the type #45098

midgleyc opened this issue Jul 19, 2021 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@midgleyc
Copy link

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
}
@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 19, 2021

See the comments on #42687.

Duplicate of #27706.

@midgleyc
Copy link
Author

Thanks!

I note that the most general case #36579 has been marked as "Working as Intended". Most of the other tickets are still in discussion mode. Is narrowing unknown types on assignment a possibility? I'm not really concerned about other types: for the most part, they're much easier to work with.

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Jul 21, 2021
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' 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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants