Closed
Description
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
}