-
Notifications
You must be signed in to change notification settings - Fork 12.8k
asserts x is type
doesn't work when using arrow functions
#34523
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
This is (perhaps unfortunately) working as intended, as per #33622. |
Thanks for looking into it! Nothing I cannot work around in the end. Just felt surprising / inconsistent :) |
TS casts the `required` assert function to a const, then pukes on the assertion see microsoft/TypeScript#34523 (comment)
TS casts the `required` assert function to a const, then pukes on the assertion see microsoft/TypeScript#34523 (comment)
As mentioned here (#33622 (comment)) a workaround is:
|
A better error message on this design limitation would have been nice instead of the confusing TS 2775 |
I created a new issue for that: #53450 |
Is there a way to type object literal members in the above way? I can't seem to get either to work: const assertions = {
isString(val: unknown): asserts val is string {
if (typeof val !== "string") throw new Error("Nope");
},
isString2: (val: unknown): asserts val is string => {
if (typeof val !== "string") throw new Error("Nope");
}
} |
Just like pstrh this comment said. const assertions: {
isString: (val: unknown) => asserts val is string;
isString2: (val: unknown) => asserts val is string;
} = {
isString(val) {
if (typeof val !== "string") throw new Error("Nope");
},
isString2: (val) => {
if (typeof val !== "string") throw new Error("Nope");
}
}
const x: unknown = '123';
assertions.isString(x)
x.toLowerCase(); |
TypeScript Version: 3.7.0-dev.20191016
Search Terms: assertion signatures, asserts, asserts is type
Code
Expected behavior:
Compiles, infers that
x
is a string, both when using onlyisString1
orisString2
Actual behavior:
Compile error on
isString2
:Playground Link: 1⃣ playground
Related Issues: #33743
Context
In principle the above problem is easy to work around, however, the result of it is when type checkers are stored on objects, the above error returns as is demonstrated in 2⃣ this playground. Note how the very same function fails when it is stored in an object, unless the type is provided explicitly.
The text was updated successfully, but these errors were encountered: