microsoft / TypeScript Public
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
Docs: "Type assertion" vs "asserts" keyword #35653
Comments
I like to call the I never liked the word "cast" for it because it implies something else in other programming languages. |
Hmm, maybe function as<T>(x: any): asserts x is T { }
// proper use
let exprAssertGood = Math.random() < 3 ? "hello" : 123;
(exprAssertGood as string).toUpperCase();
// proper use
let stmtAssertGood = Math.random() < 3 ? "hello" : 123;
as<string>(stmtAssertGood);
stmtAssertGood.toUpperCase(); // okay
// improper use
let exprAssertBad = Math.random() < 3 ? "hello" : 123;
exprAssertBad as string;
exprAssertBad.toUpperCase(); // error, prior assertion only existed in the immediate expression
// improper use
let stmtAssertBad = Math.random() < 3 ? "hello" : 123;
as<string>(stmtAssertBad).toUpperCase(); // error, assertion is a void expression |
Disclaimer: my opinion "assertion" in these cases means that you're telling the compiler what a type is, and the compiler will trust you know what you're doing e.g.
|
I like both @orta and @jcalz's ideas! The book revision is ready to go, pending this decision. One other thing that may be worth indicating in the name is that |
Hey there!
I’m updating Programming TypeScript to include assertions in control flow analysis, and was looking for guidance about naming.
Type assertions (
x as T
) and assertions in control flow analysis (asserts x is T
) are similarly named. What’s a good way to call these these features, in a way that doesn’t confuse people and aligns with the way the TS team is communicating it?A couple of ideas:
x as T
to “type coercion” or “type casting" (even though it’s not a runtime behavior), and callasserts x is T
a “type assertion”x as T
as-is (“type assertion”), and callasserts x is T
a “user-defined type assertion”, similar to a “user-defined type guard”Thanks!
The text was updated successfully, but these errors were encountered: