Skip to content

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 import and export (preferred).
  • Namespaces: An older way to group code (less common now).
  • Functions: Blocks of reusable code.
  • Variables: Named storage for data (using let and const).
  • 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.

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 message with an explicit type annotation : string and assigns it a string value.
  • Line 5: Defines a function greet that accepts one parameter text of type string and has a return type of void (meaning it doesn’t return a value).
  • Line 6: Uses console.log (a standard JavaScript function) to print the text.
  • Line 9: Calls the greet function, passing the message variable as an argument.

TypeScript code needs to be compiled into JavaScript before it can be executed by browsers or Node.js.

  1. Save: Save your code in a file with a .ts extension (e.g., hello.ts).
  2. 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).
  3. 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.

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:

OptionDescription
targetSpecifies the target ECMAScript version for the output JavaScript (e.g., "ES2016", "ESNext").
moduleSpecifies the module system for the output code (e.g., "CommonJS", "ES2020", "NodeNext").
outDirRedirects compiled JavaScript output to a specified directory (e.g., "./dist").
rootDirSpecifies the root directory of your source .ts files.
strictEnables a set of strict type-checking options (recommended for new projects).
esModuleInteropImproves compatibility when importing CommonJS modules.
sourceMapGenerates 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.

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.

Reserved words with special meaning (e.g., let, const, class, interface, function, if, else, for, while, import, export, type, public, private, protected).

TypeScript ignores spaces, tabs, and newlines (whitespace) that are not part of string literals. Use whitespace to format code for readability.

TypeScript is case-sensitive (variable and Variable are distinct).

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.

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}`);
}

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.