TypeScript Basic Types
A type tells TypeScript what kind of value a variable can hold.
Type Annotations
Write a colon and the type after the variable name:
Example
let studentName: string = "Ayesha";
let age: number = 20;
let isEnrolled: boolean = true;
console.log(studentName, age, isEnrolled);Ayesha 20 true
If you assign the wrong kind of value, TypeScript shows an error:
Example
let age: number = 20;
age = "twenty";error TS2322: Type 'string' is not assignable to type 'number'.
The Primitive Types
| Type | Example values | Used for |
|---|---|---|
string | "Karachi", 'Ali' | Text |
number | 42, 99.5 | All numbers |
boolean | true, false | Yes or no |
bigint | 100n | Very large whole numbers |
null | null | Empty on purpose |
undefined | undefined | Not set yet |
symbol | Symbol("id") | Unique keys |
Write type names in lowercase: string, not String.
Type Inference
When you give a value straight away, you can skip the annotation. TypeScript infers the type:
Example
let shop = "Hassan Garments"; // inferred as string
let items = 12; // inferred as number
items = items + 1; // fine
// shop = 5; // Error: Type 'number' is not assignable to type 'string'Let TypeScript infer simple variables. Write annotations for function parameters and for variables that start without a value.
any
any turns type checking off for a variable. It can hold anything, and TypeScript will not complain about anything you do with it.
Example
let data: any = "hello";
data = 10;
data.foo.bar(); // no error while compiling, but it crashes when it runsAvoid any. It removes the safety TypeScript gives you.
unknown
unknown also accepts any value, but you must check its type before using it. It is the safe version of any.
Example
let input: unknown = "0300-1234567";
if (typeof input === "string") {
console.log(input.length); // allowed: TypeScript knows it is a string here
}12
void and never
voidis used for functions that return nothingneveris used for functions that never finish, for example one that always throws an error
Example
function logMessage(msg: string): void {
console.log(msg);
}
function fail(reason: string): never {
throw new Error(reason);
}Enums
An enum gives friendly names to a fixed set of values:
Example
enum OrderStatus {
Pending = "PENDING",
Shipped = "SHIPPED",
Delivered = "DELIVERED"
}
let status: OrderStatus = OrderStatus.Shipped;
console.log(status);SHIPPED
Many developers prefer union types (taught later) instead of enums, but you will see enums in many projects.
Exercise
Exercise
Which type is the safer choice when you do not know a value's type in advance?
