Understanding TypeScript Syntax: The Basics

November 2, 2024

Understanding TypeScript Syntax: The Basics

This lesson dives into the fundamental syntax of TypeScript. We will explore variables, data types, and operators, providing examples to illustrate how they differ from JavaScript.

Variables in TypeScript

In TypeScript, we declare variables using the same keywords as in JavaScript: let, const, and var. However, TypeScript adds a powerful feature: type annotations. This allows us to specify the type of a variable at the time of declaration.

Using let and const

Here’s how you can declare variables in TypeScript:

let name: string = 'John';
const age: number = 30;

In the example above, we declared a variable name of type string and a constant age of type number.

Data Types in TypeScript

TypeScript provides several built-in data types that help us define the kind of data a variable can hold. Below are some of the most commonly used data types:

  • string: Represents textual data.
  • number: Represents numeric values.
  • boolean: Represents true/false values.
  • any: A flexible type that can hold any value.
  • void: Represents the absence of a value, typically used in functions.
  • array: Represents a collection of values of a specific type.

Here’s an example demonstrating various data types:

let isActive: boolean = true;
let score: number = 100;
let userName: string = 'Alice';
let userRoles: string[] = ['admin', 'editor'];

Operators in TypeScript

TypeScript supports all the operators available in JavaScript, including arithmetic, comparison, and logical operators. However, with type annotations, TypeScript can provide better type checking during compile time.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations:

let sum: number = 10 + 5;
let difference: number = 10 - 5;

Comparison Operators

Comparison operators are used to compare two values:

let isEqual: boolean = (10 === 10);
let isGreater: boolean = (10 > 5);

Logical Operators

Logical operators are used to combine boolean values:

let isTrue: boolean = (true && false);
let isEither: boolean = (true || false);

Conclusion

Understanding the basic syntax of TypeScript is essential for leveraging its powerful features. By using type annotations, TypeScript helps catch errors at compile time, making your code more robust and maintainable. In this lesson, we covered how to declare variables, the different data types available, and the operators you can use. In the next lesson, we will dive deeper into functions and how to define them in TypeScript.