TypeScript Basic Syntax
TypeScript syntax is a superset of JavaScript syntax. This means any valid JavaScript code is valid TypeScript code. This section will introduce some basic syntax elements that make up a TypeScript program.
Case Sensitivity
Like JavaScript, TypeScript is case-sensitive. This means variable names, function names, keywords, etc. must use the correct case.
Comments
Comments are used to explain code and are ignored by the TypeScript compiler, not appearing in the final JavaScript file. TypeScript supports two types of comments:
-
Single-line comments: Start with
//and continue to the end of the line. -
Multi-line comments: Start with
/*and end with*/, can span multiple lines.
Statements and Semicolons
TypeScript programs consist of a series of statements. A statement typically performs an operation. For example, declaring a variable or calling a function.
Semicolons (;) are used to separate statements. In TypeScript, semicolons are optional. If you write only one statement per line, you can omit the semicolon. The TypeScript compiler will automatically add semicolons at line ends (this process is called ASI - Automatic Semicolon Insertion).
However, to keep code clear and avoid some potential errors, it's recommended to always add semicolons at the end of statements.
Identifiers and Keywords
Identifiers are names you give to variables, functions, classes, modules, etc. Identifier naming rules are:
- Can contain letters, numbers, underscores (
_), and dollar signs ($). - Must start with a letter, underscore, or dollar sign, cannot start with a number.
- Cannot be TypeScript keywords or reserved words.
Keywords are reserved words in TypeScript with special meanings that cannot be used as identifiers. Common keywords include:
break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, export, extends, false, finally, for, function, if, import, in, instanceof, new, null, return, super, switch, this, throw, true, try, typeof, var, void, while, with, as, implements, interface, let, package, private, protected, public, static, yield.
Whitespace and Line Breaks
TypeScript ignores extra spaces, tabs, and line breaks in code. This allows you to freely format code to improve readability.
For example, the following three styles are equivalent:
Typically, we use code formatting tools (like Prettier) to maintain consistent code style throughout the project.