TypeScript Tutorial menu

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

typescript
let studentName: string = "Ayesha";
let age: number = 20;
let isEnrolled: boolean = true;

console.log(studentName, age, isEnrolled);
Output
Ayesha 20 true

If you assign the wrong kind of value, TypeScript shows an error:

Example

typescript
let age: number = 20;
age = "twenty";
Output
error TS2322: Type 'string' is not assignable to type 'number'.

The Primitive Types

TypeExample valuesUsed for
string"Karachi", 'Ali'Text
number42, 99.5All numbers
booleantrue, falseYes or no
bigint100nVery large whole numbers
nullnullEmpty on purpose
undefinedundefinedNot set yet
symbolSymbol("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

typescript
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

typescript
let data: any = "hello";
data = 10;
data.foo.bar();   // no error while compiling, but it crashes when it runs

Avoid 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

typescript
let input: unknown = "0300-1234567";

if (typeof input === "string") {
  console.log(input.length);   // allowed: TypeScript knows it is a string here
}
Output
12

void and never

  • void is used for functions that return nothing
  • never is used for functions that never finish, for example one that always throws an error

Example

typescript
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

typescript
enum OrderStatus {
  Pending = "PENDING",
  Shipped = "SHIPPED",
  Delivered = "DELIVERED"
}

let status: OrderStatus = OrderStatus.Shipped;
console.log(status);
Output
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?

Learn TypeScript with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp