Introduction to TypeScript Syntax
TypeScript syntax defines the rules for writing valid TypeScript programs. Because TypeScript builds on JavaScript, many familiar JavaScript constructs remain the same, including variables, operators, functions, conditions, loops, and objects. TypeScript extends these constructs with type annotations, interfaces, type aliases, and other features that help describe how values should be used.
Understanding the syntax is the first step toward writing programs that are easy to read, maintain, and debug. You need to know how to declare variables, define functions, organize expressions, work with data structures, and use types to communicate your intentions to the compiler.
TypeScript source files commonly use the .ts extension. Files containing JSX syntax, such as React components, generally use .tsx. The TypeScript compiler checks the source and can generate JavaScript for the target environment.
1. Basic Structure of a TypeScript Program
A TypeScript program can contain variable declarations, function definitions, expressions, imports, exports, and other statements. Statements perform operations, while expressions produce values that can be assigned, returned, or passed to functions.
const courseName: string = "TypeScript";
const duration: number = 8;
function displayCourse(): void {
console.log(courseName);
console.log(duration);
}
displayCourse();
The example declares two constants, defines a function, and calls that function. The colon followed by a type name introduces a type annotation. The void return type indicates that the function is not intended to return a meaningful value to its caller.
Statements are commonly separated by line breaks and may optionally end with semicolons. TypeScript supports JavaScript's automatic semicolon insertion, but consistent formatting helps prevent confusing code and makes programs easier to read.
2. Variables and Constants
Variables store values that a program can use later. TypeScript supports JavaScript's let, const, and var declarations. Modern code generally prefers const by default and uses let when a binding needs to be reassigned.
let score: number = 80;
score = 95;
const username: string = "Asha";
const isActive: boolean = true;
console.log(score);
console.log(username);
console.log(isActive);
The let declaration allows the score variable to receive a new value. The const declarations cannot be reassigned after initialization.
A const binding does not automatically make an object or array immutable. It prevents reassignment of the binding, but the properties of an object or the elements of an array may still be changed unless additional restrictions are applied.
const scores: number[] = [70, 80, 90];
scores.push(100); // Valid
console.log(scores);
// Compile-time error:
// scores = [10, 20];
3. Type Annotations
Type annotations explicitly specify the expected type of a variable, function parameter, return value, or object property. The colon character introduces the type annotation in common TypeScript declarations.
let title: string = "TypeScript Basics";
let lessonCount: number = 12;
let completed: boolean = false;
let topics: string[] = [
"Variables",
"Functions",
"Objects"
];
console.log(title);
console.log(lessonCount);
console.log(completed);
console.log(topics);
In this example, the variables use string, number, boolean, and string array types. TypeScript checks whether the assigned values are compatible with their declarations.
A type annotation does not convert a value into the requested type. Declaring a variable as a number will not transform an input string into a number; incompatible assignments must be corrected or explicitly handled through appropriate conversion and validation logic.
4. Type Inference
Type inference allows TypeScript to determine types from initial values and expressions. This means that explicit annotations are not necessary for every declaration.
const language = "TypeScript";
// Inferred type: string
const price = 49.99;
// Inferred type: number
const published = true;
// Inferred type: boolean
function addNumbers(first: number, second: number) {
return first + second;
}
// Inferred return type: number
const total = addNumbers(10, 20);
console.log(language, price, published, total);
TypeScript infers the types of the constants from their initial values. It also infers the return type of addNumbers() because the parameters are numeric and the function returns their sum.
Use inference when it makes straightforward code easier to read. Explicit annotations are helpful when they clarify a function's contract, document shared data structures, or make complex behavior easier to understand.
5. Identifiers and Naming Rules
Identifiers are names used for variables, functions, classes, interfaces, and other declarations. TypeScript follows JavaScript identifier rules, allowing letters, underscores, dollar signs, and many Unicode characters in permitted positions. Digits may appear after the first character but cannot begin a standard identifier.
const courseName = "TypeScript";
const _retryCount = 3;
const $elementId = "course-title";
const lesson2 = "Functions";
function calculateTotal(): number {
return 100;
}
console.log(courseName);
console.log(_retryCount);
console.log($elementId);
console.log(lesson2);
console.log(calculateTotal());
Identifiers are case-sensitive, so courseName and coursename refer to different names. Reserved keywords cannot generally be used as ordinary identifiers in declaration positions.
Although several naming styles are valid, consistency matters in real projects. A common convention is camelCase for variables and functions, PascalCase for classes and interfaces, and descriptive names that communicate the role of each declaration.
6. Comments in TypeScript
Comments explain code to developers and are ignored as executable statements. TypeScript supports single-line comments and multiline comments using JavaScript syntax.
// This is a single-line comment.
const maxAttempts = 3;
/*
This is a multiline comment.
It can explain a more complex operation.
*/
function canRetry(attempt: number): boolean {
return attempt < maxAttempts;
}
console.log(canRetry(1));
TypeScript also supports documentation comments that begin with three slashes or, more commonly, the JSDoc-style opening /**. These comments can document functions, parameters, return values, and public APIs.
/**
* Calculates the total price.
* @param price Unit price.
* @param quantity Number of units.
* @returns The calculated total.
*/
function calculateTotal(
price: number,
quantity: number
): number {
return price * quantity;
}
Use comments to explain intent, constraints, or decisions that are not obvious from the code. Avoid repeating what a clear function name or straightforward expression already communicates.
7. Operators and Expressions
Operators perform operations on values. TypeScript supports JavaScript operators for arithmetic, comparison, logical conditions, assignment, and other expressions, while its type system checks whether an operation is valid for the types involved.
const first = 20;
const second = 5;
const sum = first + second;
const difference = first - second;
const product = first * second;
const quotient = first / second;
const isGreater = first > second;
const isEqual = first === second;
const canContinue = isGreater && !isEqual;
console.log(sum);
console.log(difference);
console.log(product);
console.log(quotient);
console.log(isGreater);
console.log(isEqual);
console.log(canContinue);
Arithmetic operators calculate numeric results, comparison operators produce Boolean values, and logical operators combine conditions. The strict equality operator (===) compares values without performing the type coercion associated with loose equality.
TypeScript checks many invalid operations during development, but it does not eliminate every runtime issue. For example, a numeric value can still be NaN or infinite, and external data may not match its declared type unless validated.
8. Strings and Template Literals
Strings represent text. TypeScript supports single-quoted strings, double-quoted strings, and JavaScript template literals enclosed in backticks. Template literals are useful for embedding expressions directly into strings.
const username = "Asha";
const course = "TypeScript";
const duration = 8;
const greeting = "Hello, " + username + "!";
const description =
`Learn ${course} in ${duration} hours.`;
console.log(greeting);
console.log(description);
Template literals use the dollar sign and curly braces to evaluate an expression inside a string. The expression can contain a variable, a calculation, or another valid JavaScript expression.
TypeScript checks the expressions in template literals according to their types, just as it does in other parts of the program. This syntax is often more readable than combining numerous strings with the plus operator.
9. Arrays and Object Literals
Arrays store ordered collections of values, while objects group related properties into a single value. TypeScript adds type checking to these structures so developers can describe the expected elements and properties.
const scores: number[] = [80, 90, 95];
interface Course {
id: number;
title: string;
published: boolean;
}
const course: Course = {
id: 101,
title: "TypeScript Basics",
published: true
};
console.log(scores[0]);
console.log(course.title);
console.log(course.published);
The array annotation specifies that its elements should be numbers. The Course interface defines an object shape with an identifier, title, and publication status.
Object properties can be optional or readonly when the application requires those behaviors. Type aliases and interfaces also make it easier to reuse object contracts across functions and modules.
10. Conditional Statements
Conditional statements let a program select which code to execute based on a condition. TypeScript uses the same basic conditional syntax as JavaScript and checks that expressions and branches are used appropriately.
const score = 85;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 70) {
console.log("Good");
} else {
console.log("Keep practicing");
}
The if branch runs when its condition is true. The else if branch checks another condition when the preceding condition fails, and the else branch handles the remaining cases.
TypeScript can also narrow variable types inside conditional branches. For example, checking whether a value is a string allows TypeScript to treat it as a string inside the corresponding branch when its original type was a union.
11. Loops
Loops repeat operations while a condition holds or iterate through values in a collection. TypeScript supports common JavaScript loop structures, including for loops, while loops, and for...of loops.
const courses: string[] = [
"HTML",
"CSS",
"TypeScript"
];
for (let index = 0; index < courses.length; index++) {
console.log(courses[index]);
}
for (const course of courses) {
console.log("Learning:", course);
}
The traditional for loop gives direct control over initialization, condition checking, and incrementing. The for...of loop iterates over values in an iterable, such as an array.
TypeScript infers the type of each course as a string because the array is declared as string[]. Accurate collection types help ensure that values are used with compatible operations inside loops.
12. Functions and Return Types
Functions encapsulate reusable operations. TypeScript allows developers to declare the types of function parameters and return values, making the function's contract visible to callers.
function calculateArea(
width: number,
height: number
): number {
return width * height;
}
function displayMessage(message: string): void {
console.log(message);
}
console.log(calculateArea(10, 5));
displayMessage("TypeScript functions");
The calculateArea() function returns a number, while displayMessage() performs an action and has a void return annotation.
TypeScript can infer many return types, but explicit annotations are often useful for exported functions, shared service contracts, and complex operations where the expected result should remain clear.
13. Modules, Imports, and Exports
Modules let developers divide a project into separate files with explicit dependencies. An exported declaration can be imported by another module, allowing functions and types to be reused without placing the entire application in one file.
For example, create a file named math.ts:
export function add(
first: number,
second: number
): number {
return first + second;
}
In another file, import and use the exported function:
import { add } from "./math";
console.log(add(10, 20));
The import path and module format must be compatible with the project's compiler settings and runtime or bundler. Module conventions can differ between CommonJS projects, ECMAScript module projects, and framework-managed applications.
TypeScript also supports type-only imports and exports, which explicitly mark declarations used only for type checking. They help communicate the difference between runtime values and compile-time types.
14. TypeScript Syntax Errors and Best Practices
TypeScript syntax and type errors may appear similar, but they represent different problems. A syntax error means the code does not follow the language grammar. A type error means the code is syntactically valid but violates a type rule or a required type relationship.
let count: number = 10;
// Type error:
// count = "ten";
function add(first: number, second: number): number {
return first + second;
}
// Type error:
// add("10", 20);
The declarations are valid TypeScript syntax. The commented assignments and function call illustrate type errors because strings are supplied where numbers are required.
Follow these practices when writing TypeScript:
- Use const by default and let when reassignment is required.
- Choose descriptive, consistent identifier names.
- Use type inference for straightforward local variables.
- Define clear types for function parameters and important return contracts.
- Use interfaces and type aliases for reusable data structures.
- Enable strict compiler checks when practical.
- Resolve compiler errors rather than suppressing them without understanding the cause.
- Use runtime validation when data comes from an external or untrusted source.
Conclusion
TypeScript syntax builds on JavaScript with additional constructs for defining and checking types. Variables, operators, expressions, functions, conditions, loops, arrays, objects, and modules follow familiar JavaScript patterns, while annotations and type definitions help communicate how values should be used.
Begin by practicing declarations, annotations, inference, functions, and object structures. As your understanding improves, apply modules, unions, interfaces, generics, and stricter compiler settings to organize larger applications. Consistent syntax and accurate types provide a strong foundation for writing reliable and maintainable TypeScript code.