TypeScript - Basic Syntax
TypeScript - Basic Syntax
Section titled “TypeScript - Basic Syntax”TypeScript syntax is fundamentally based on JavaScript syntax (specifically, modern ECMAScript standards). If you know JavaScript, you already know much of TypeScript’s syntax. TypeScript adds type annotations and specific constructs like interface, enum, and namespace.
A TypeScript program consists of:
- Modules: Code organized into separate files using
importandexport(preferred). - Namespaces: An older way to group code (less common now).
- Functions: Blocks of reusable code.
- Variables: Named storage for data (using
letandconst). - Classes: Blueprints for creating objects.
- Interfaces: Contracts defining the shape of objects.
- Statements and Expressions: Instructions that perform actions.
- Comments: Explanatory text ignored by the compiler.
Your First TypeScript Code
Section titled “Your First TypeScript Code”Let’s look at a simple “Hello World” example with a type annotation:
// File: hello.ts
const message: string = "Hello, TypeScript World!";
function greet(text: string): void { console.log(text);}
greet(message);Key elements:
- Line 3: Declares a constant variable
messagewith an explicit type annotation: stringand assigns it a string value. - Line 5: Defines a function
greetthat accepts one parametertextof typestringand has a return type ofvoid(meaning it doesn’t return a value). - Line 6: Uses
console.log(a standard JavaScript function) to print the text. - Line 9: Calls the
greetfunction, passing themessagevariable as an argument.
Compiling and Executing TypeScript
Section titled “Compiling and Executing TypeScript”TypeScript code needs to be compiled into JavaScript before it can be executed by browsers or Node.js.
- Save: Save your code in a file with a
.tsextension (e.g.,hello.ts). - Compile: Open your terminal or command prompt, navigate to the file’s directory, and run the TypeScript compiler (
tsc):tsc hello.ts. This will generate a corresponding JavaScript file (e.g.,hello.js). - Execute: Run the generated JavaScript file using Node.js:
node hello.js.
Compiled JavaScript (hello.js):
var message = "Hello, TypeScript World!";function greet(text) { console.log(text);}greet(message);// Note: The exact output depends on your tsconfig.json target settings.// This example assumes an older target like ES3/ES5.For development, tools like ts-node allow you to execute .ts files directly without a separate compilation step (ts-node hello.ts). For projects, you typically configure compilation using a tsconfig.json file.
tsconfig.json and Compiler Options
Section titled “tsconfig.json and Compiler Options”For any non-trivial project, you should use a tsconfig.json file in the root directory to configure the TypeScript compiler. You can generate a default one using tsc --init.
Key options often configured in tsconfig.json:
| Option | Description |
|---|---|
target | Specifies the target ECMAScript version for the output JavaScript (e.g., "ES2016", "ESNext"). |
module | Specifies the module system for the output code (e.g., "CommonJS", "ES2020", "NodeNext"). |
outDir | Redirects compiled JavaScript output to a specified directory (e.g., "./dist"). |
rootDir | Specifies the root directory of your source .ts files. |
strict | Enables a set of strict type-checking options (recommended for new projects). |
esModuleInterop | Improves compatibility when importing CommonJS modules. |
sourceMap | Generates corresponding .map files for debugging the original TypeScript code. |
noImplicitAny | (Part of strict) Raises errors on expressions and declarations with an implied any type. |
Running tsc in a directory with tsconfig.json will compile the project according to these settings.
Identifiers
Section titled “Identifiers”Names given to variables, functions, classes, etc. Follow standard JavaScript rules: must start with a letter, _, or $, can contain letters, digits, _, $. Case-sensitive. Cannot be reserved keywords.
Keywords
Section titled “Keywords”Reserved words with special meaning (e.g., let, const, class, interface, function, if, else, for, while, import, export, type, public, private, protected).
Whitespace and Line Breaks
Section titled “Whitespace and Line Breaks”TypeScript ignores spaces, tabs, and newlines (whitespace) that are not part of string literals. Use whitespace to format code for readability.
Case Sensitivity
Section titled “Case Sensitivity”TypeScript is case-sensitive (variable and Variable are distinct).
Semicolons
Section titled “Semicolons”Semicolons (;) are technically optional in TypeScript (like JavaScript) due to Automatic Semicolon Insertion (ASI). However, it’s generally considered best practice to include semicolons at the end of statements to avoid potential ambiguity and ensure consistent code behavior.
Comments
Section titled “Comments”Used to add explanatory notes to code, ignored by the compiler.
// This is a single-line comment
/* This is a multi-line comment.*/
/** * This is a JSDoc comment, often used for documentation generation. * @param name The name to greet */function greetWithDoc(name: string): void { console.log(`Hello, ${name}`);}Object-Oriented Concepts
Section titled “Object-Oriented Concepts”TypeScript fully supports object-oriented programming (OOP) principles with first-class support for classes, interfaces, inheritance (extends), and access modifiers (public, private, protected).
class Greeter { private greeting: string;
constructor(message: string) { this.greeting = message; }
greet(): void { console.log(this.greeting); }}
const myGreeter = new Greeter("Welcome to OOP in TypeScript!");myGreeter.greet();This basic syntax forms the foundation for writing TypeScript code. Subsequent sections will delve deeper into specific features like types, functions, classes, modules, and more.