CodeToLive

Variables and Data Types in TypeScript

TypeScript introduces static typing to JavaScript. Variables must be declared with a specific type, and the TypeScript compiler ensures that the variable is used correctly throughout the code.

Declaring Variables

In TypeScript, you can declare variables using let, const, or var. The type of the variable is specified using a colon (:) followed by the type.


let age: number = 25;  // Number
const name: string = "Alice";  // String
var isStudent: boolean = true;  // Boolean
      

Type Inference

TypeScript can infer the type of a variable based on its initial value. For example:


let score = 100;  // TypeScript infers `score` as `number`
let greeting = "Hello";  // TypeScript infers `greeting` as `string`
      

Common Data Types

Example:


let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;
let scores: number[] = [90, 85, 95];
let person: { name: string, age: number } = { name: "Alice", age: 25 };
      
Next: Control Structures