Skip to content

Expert · TypeScript basics · topic 43 of 61 · 25 min

Basic types and inference

Explanation

The basic types are string, number, boolean, arrays (number[]), tuples ([string, number]) and literal types like "GET" | "POST". any switches checking off, unknown is the safe "I don't know yet" type, void means "returns nothing" and never means "cannot happen". With strictNullChecks, null and undefined must be written in the type when allowed.

Primitive types

typescript
let name: string = 'Asha';
let age: number = 29;
let isActive: boolean = true;
let big: bigint = 10n;
// In practice, let inference do this: let name = 'Asha';

Arrays and tuples

typescript
const marks: number[] = [78, 92];          // or Array<number>
const names: string[] = [];
const point: [number, number] = [18.52, 73.85];  // a tuple: fixed length and types
const entry: [string, number] = ['rice', 40];
marks.push('ninety');  // Error: string is not assignable to number

Functions

typescript
function addGst(amount: number, rate: number = 18): number {
  return amount * (1 + rate / 100);
}
function greet(name: string, title?: string): string {   // ? = optional
  return title ? `${title} ${name}` : name;
}
function logVisit(page: string): void {   // void: returns nothing useful
  console.log('visited', page);
}
const double = (n: number): number => n * 2;

Literal types and unions

A literal type is one exact value: 'GET' or 42. Combined with | (union, meaning "one of these"), they describe a fixed set of allowed values. This catches typos like 'POTS' at compile time.

typescript
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
function request(method: Method, url: string) { /* … */ }
request('POST', '/orders');   // OK
request('POTS', '/orders');   // Error: '"POTS"' is not assignable to type 'Method'.

null and undefined

With strictNullChecks (part of strict), a string variable cannot hold null. If a value can be missing, say so in the type: string | null. Then TypeScript forces you to check before using it.

typescript
function findUser(id: number): { name: string } | undefined { /* … */ return undefined; }
const user = findUser(7);
console.log(user.name);    // Error: 'user' is possibly 'undefined'.
console.log(user?.name);   // OK

any, unknown and never

TypeMeaningUse
anyAnything; checking turned offAvoid; only when migrating old code
unknownAnything, but you must check before useData from JSON.parse, APIs, user input
voidA function returns nothing usefulReturn type of loggers, handlers
neverA value that can never existFunctions that always throw; exhaustive checks
typescript
const data: unknown = JSON.parse('{"amount": 5}');
data.amount;                       // Error: 'data' is of type 'unknown'.
if (typeof data === 'object' && data !== null && 'amount' in data) {
  console.log((data as { amount: number }).amount);  // allowed after checking
}
Careful: as (a type assertion) tells the compiler "trust me". It does not convert or check anything at run time. const n = '5' as unknown as number compiles, but n is still the string '5'. Use assertions sparingly and only after a real check.
Think of it like this: any is like a security gate left open: anyone walks in unchecked. unknown is a gate with a guard: anything may arrive, but it must show ID (a type check) before going further.
Tip: Hover over any variable in VS Code to see the type TypeScript inferred. It is the fastest way to learn what the compiler thinks.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Basic types and inference · 1/6

Basic types

In this lesson you will use TypeScript's basic types.

Prefer a video by a teacher? Find free videos on “typescript basic types union literal unknown vs any” on YouTube ↗

In real life: Typing an API request helper

An internal tool at a bank calls dozens of endpoints. A typed helper accepts only the four allowed HTTP methods and a body that is an object, so a typo like "DELET" or passing a number as the body is caught in the editor.

typescript
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
function buildRequest(method: Method, url: string, body?: object) {
  return { method, url, body: body ? JSON.stringify(body) : undefined };
}
buildRequest('POST', '/accounts', { name: 'Asha' });

Practice (0/3 done)

Task 1 · Code · Typescript

Write average(marks: number[]): number that returns the average, or 0 for an empty array.

Task 2 · Code · Typescript

type Method = "GET" | "POST" | "PUT" | "DELETE". Write isMethod(value: string): boolean that returns true only for those four exact strings (this is the run-time check that matches the type).

Task 3 · Code · Typescript

Write describePoint(p: [number, number]): string that returns "lat <a>, lng <b>" with each number rounded to 2 decimals using toFixed(2).

Quick quiz

Question 1

1.How do you write "an array of strings"?

Question 2

2.Which type forces you to check a value before using it?

Question 3

3.type Size = 'S' | 'M' | 'L'; const s: Size = 'XL'; What happens?

Question 4

4.What does "x as number" do at run time?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How do you write "an array of strings"?

Answer: string[]

string[] (or Array<string>) is an array of strings. [string] is a tuple of exactly one.

Which type forces you to check a value before using it?

Answer: unknown

unknown accepts anything but blocks use until narrowed.

type Size = 'S' | 'M' | 'L'; const s: Size = 'XL'; What happens?

Answer: Compile error

'XL' is not one of the allowed literal types.

What does "x as number" do at run time?

Answer: Nothing; it only affects type checking

Assertions are erased; no conversion happens.

Why write const unreachable: never = p; in the default branch of a switch over a union?Related

Answer: It gives a compile error if a new member is added to the union but not handled

If every case is handled, p is never there. A missed case leaves a real type, which cannot be assigned to never.

From Unions and narrowing

Which of these is NOT a primitive type?Related

Answer: array

Arrays are objects. The primitives are string, number, bigint, boolean, undefined, null and symbol.

From Values and types

Why is unknown safer than any?Related

Answer: With unknown you must check the type before using the value; any turns checking off

any lets you do anything, even things that crash. unknown forces a check like typeof first.

From Why TypeScript

How many primitive types does Java have?Related

Answer: 8

byte, short, int, long, float, double, char, boolean.

From Variables and primitive types

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “TypeScript basics” before its exam: Object types, interfaces and unions, Generics, Utility types and real-world TypeScript.
  2. Module 9 exam: TypeScript basics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functional patterns and testing. 61 topics left in the course before the final exam.

← Previous: Why TypeScript