TypeScript Syntax and Data Types

TypeScript is a superset of JavaScript, which means it adds additional features and functionality to the already familiar JavaScript syntax. By introducing static typing, TypeScript allows developers to catch errors at compile-time and enhance the development process.

Basic Syntax

In TypeScript, the syntax is similar to JavaScript, with some additional features. Here are a few notable differences:

Variable Declaration

To declare variables in TypeScript, you can use the let or const keywords, similar to JavaScript. However, TypeScript also introduces the type annotation, where you can explicitly declare the data type of a variable.

let num: number = 10;
const message: string = "Hello, TypeScript!";

Functions

In TypeScript, you can define functions using the function keyword, just like in JavaScript. Additionally, TypeScript supports type annotations for function parameters and return types.

function addNumbers(a: number, b: number): number {
  return a + b;
}

Classes

TypeScript enables object-oriented programming with the use of classes. You can define classes using the class keyword, and you can also specify access modifiers and implement interfaces.

class Person {
  private name: string;
  constructor(name: string) {
    this.name = name;
  }
  greet(): void {
    console.log(`Hello, ${this.name}!`);
  }
}

Data Types

TypeScript introduces static typing, which means variables can have specific data types. Here are some commonly used data types in TypeScript:

Primitive Types

  • boolean: represents a logical value (either true or false).
  • number: represents numerical data.
  • string: represents textual data enclosed in quotes.
let isCompleted: boolean = false;
let count: number = 5;
let message: string = "Hello, TypeScript!";

Arrays

Arrays in TypeScript allow you to define a collection of values of the same data type.

let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ["apple", "banana", "orange"];

Objects

Objects in TypeScript are similar to JavaScript objects, allowing you to define properties and their data types.

let person: { name: string; age: number } = {
  name: "John Doe",
  age: 25,
};

Any

The any data type in TypeScript allows variables to have dynamic typing, similar to regular JavaScript.

let dynamicValue: any = true;
dynamicValue = "TypeScript";
dynamicValue = 42;

Union Types

Union types allow a variable to have multiple data types. It is denoted by a pipe (|) symbol.

let userInput: string | number;
userInput = "TypeScript";
userInput = 42;

TypeScript's syntax and data types provide powerful tools for building robust and maintainable applications. By incorporating static typing into JavaScript, TypeScript ensures more predictable code and helps catch errors early in the development process.


noob to master © copyleft