-
Notifications
You must be signed in to change notification settings - Fork 12.8k
unknown
isnβt narrowed by assignment
#43584
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
Comments
I've discovered that function f(request: {params: {[param: string]: unknown;}}) {
let x = request.params.x;
try {
x = validate(x);
takesString(x)
} catch (e) {} also fails to compile. So maybe the issue is related to narrowing the type of a variable in a broader scope? |
unknown
isnβt narrowed by assignment
I think this is probably a better example of what youβre surprised by, if Iβm understanding you. |
Yes, that would do it.
|
I my opinion you are confused about
In your case you can use function f(request: {params: {[param: string]: any;}}) {
let x = request.params.x;
try {
x = validate(x);
} catch (e) {}
try {
takesString(x); // Fails to compile, x is of type unknown.
} catch (e) {}
}
function validate(x: any): string { return ""; }
function takesString(s: string) {} Look at Playground |
We lose type safety with function validate(x: unknown): x is string {
// blah blah blah...
}
// ...
function f(request: {params: {[param: string]: unknown;}}) {
let x = request.params.x;
if (!validate(x)) { throw SomeError(); }
// now x is narrowed to `string`
} which is what I've switched to in my code. |
I like your point:
I think you are right. Here is anohter example that ilustrates it: Playground function validate(x: unknown): x is string {
return typeof x === "string";
}
function mayBeNorS(): number|string{
if(Math.random()>0.5) return 1;
return 'x'
}
// ...
function f(request: {params: {[param: string]: unknown;}}) {
let x = request.params.x;
if (!validate(x)) { throw Error('some'); }
// now x is narrowed to `string`
x = "other";
// now x is ruined to `unknown`
x.toLocaleLowerCase();
// if the original variable was not `unkonwn` it works!
let y = mayBeNorS();
y = "other";
// now y is narrowed to `string`
y.toLocaleLowerCase();
} |
Worth noting this also happens with |
Bug Report
π Search Terms
try block
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
In this example, the code fails to compile because
tsc
has deducedx
in the second block to be of typeunknown
π Expected behavior
Since we have successfully exited the first try-catch block,
x
's type should be narrowed tostring
in the second.The text was updated successfully, but these errors were encountered: