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
- number: Represents numeric values (e.g.,
10
,3.14
). - string: Represents text data (e.g.,
"Hello"
,'TypeScript'
). - boolean: Represents true or false values.
- array: Represents an ordered collection of elements (e.g.,
number[]
,string[]
). - object: Represents key-value pairs (e.g.,
{ name: "Alice", age: 25 }
). - any: Represents a variable that can hold any type (use sparingly).
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