Skip to content

TypeScript Basic Types — Complete Beginner's Guide

DodaTech Updated 2026-06-28 8 min read

In this tutorial, you will learn about TypeScript Basic Types. We cover key concepts, practical examples, and best practices to help you master this topic.

TypeScript's basic types form the foundation of every program you'll write — string, number, boolean, arrays, tuples, and special types like any, unknown, never, and void each serve a specific purpose in expressing your data's shape and preventing bugs.

What You'll Learn

  • The primitive types: string, number, boolean
  • Array and tuple types for ordered collections
  • The special types: any, unknown, never, void, null, undefined
  • Type inference and when to annotate explicitly
  • How each type maps to real-world data

Why It Matters

Every piece of data in your program has a type — a user's name is a string, their age is a number, whether they're logged in is a boolean. Choosing the right type isn't just about satisfying the compiler; it's about documenting your intent and preventing invalid states from being representable.

Real-World Use

In the Durga Antivirus Pro dashboard, threat severity is represented as a number (1-10), virus names as strings, active scans as booleans, and scan history as arrays of tuples containing timestamp and result. Getting these types right means the difference between a dashboard that never crashes and one that intermittently displays NaN in the severity column.

Learning Path

flowchart LR
  A[Installation & Setup] --> B[Basic Types]
  B --> C[Interfaces]
  B --> D[You Are Here]
  C --> E[Type Aliases]
  E --> F[Functions]
  F --> G[Enums]

The Primitive Types

string

const name: string = "Alice";
const greeting = `Hello, ${name}!`; // Template literal — also a string
const empty: string = "";

// TypeScript catches this:
// const age: string = 42; // Error: Type 'number' is not assignable to type 'string'

Strings represent text data: names, descriptions, error messages, JSON payloads, HTML content.

number

const price: number = 29.99;
const count: number = 42;
const hex: number = 0xff;     // 255 in decimal
const binary: number = 0b1010; // 10 in decimal
const big: number = 1_000_000; // Underscores for readability

// TypeScript catches this:
// const name: number = "Alice"; // Error

Unlike other languages, TypeScript has no separate int or float — every number is a 64-bit floating point (IEEE 754).

boolean

const isActive: boolean = true;
const isComplete: boolean = false;
const hasAccess: boolean = 1 > 0; // true, from an expression

Booleans represent yes/no, on/off, enabled/disabled states.

Arrays

Arrays hold ordered collections of a single type:

const names: string[] = ["Alice", "Bob", "Charlie"];
const scores: number[] = [95, 87, 73];

// Alternative syntax (same thing):
const names2: Array<string> = ["Alice", "Bob", "Charlie"];

TypeScript prevents mixed types unless explicitly union-typed:

// const mixed: string[] = ["Alice", 42]; // Error
const mixed: (string | number)[] = ["Alice", 42]; // OK — union type

readonly Arrays

const frozen: readonly string[] = ["a", "b", "c"];
// frozen.push("d"); // Error: Property 'push' does not exist on type 'readonly string[]'

Tuples

Tuples are arrays with a fixed number of elements, each with a specific type:

// A tuple: [string, number]
const person: [string, number] = ["Alice", 30];

// Access with correct types
const pName: string = person[0];
const pAge: number = person[1];

// Error: wrong type at position
// const bad: [string, number] = [30, "Alice"]; // Error

Tuples are perfect for:

  • Return values from functions (like React's useState)
  • Coordinate pairs [x, y]
  • Key-value pairs in maps

Labeled Tuples (TS 4.0+)

type Coordinate = [x: number, y: number, z?: number];
const point: Coordinate = [10, 20];

Special Types

any — The Escape Hatch

any disables Type Checking for a value. Use it sparingly:

let data: any = 42;
data = "hello";     // OK
data = true;        // OK
data.doSomething(); // No error — but will blow up at runtime

Think of any as telling TypeScript "I know what I'm doing" — which is often not true. Prefer unknown when you genuinely don't know the type.

unknown — The Safe Any

let data: unknown = 42;
data = "hello"; // OK

// But you can't use it without narrowing:
// data.toUpperCase(); // Error: Object is of type 'unknown'

if (typeof data === "string") {
  console.log(data.toUpperCase()); // OK — narrowed to string
}

unknown forces you to prove the type before using the value. This is the safe alternative to any.

void — No Return Value

function logMessage(message: string): void {
  console.log(message);
  // No return statement needed
}

const result = logMessage("hi"); // result is void (undefined at runtime)

void means the function completes without returning a meaningful value.

never — Never Returns

function throwError(message: string): never {
  throw new Error(message);
}

function infiniteLoop(): never {
  while (true) {}
}

never is the return type for functions that never complete normally — they either throw or run forever.

null and undefined

let value1: null = null;
let value2: undefined = undefined;

// With strictNullChecks:
// let name: string = null; // Error
let name: string | null = null; // OK — union with null

With strictNullChecks: true (which you should always enable), null and undefined are not assignable to other types unless explicitly unioned.

Type Inference

You don't always need to write explicit types. TypeScript infers them:

let name = "Alice";        // inferred as string
let age = 30;               // inferred as number
let isActive = true;        // inferred as boolean
let items = [1, 2, 3];      // inferred as number[]
let obj = { x: 10, y: 20 }; // inferred as { x: number; y: number }

Add explicit annotations for:

  • Function parameters and return types
  • Public API boundaries
  • When inference isn't specific enough

Common Mistakes

1. Using any as a Default

// Bad: defeats type checking
function process(data: any) {
  return data.length; // Could crash
}

// Good: use proper type or unknown
function process(data: string) {
  return data.length; // Safe
}

2. Confusing null and undefined

let a: string | null = null;   // Deliberately empty
let b: string | undefined;     // Not yet assigned

They are different values. null is intentional absence; undefined means "not set."

3. Forgetting Tuple Order

const pair: [string, number] = ["Alice", 30];
// const wrong: [string, number] = [30, "Alice"]; // Error — wrong order

4. Using Array<any> Instead of Typed Arrays

const items: any[] = [1, "two", true]; // Loses all type safety
const typed: (string | number)[] = ["hello", 42]; // Proper union

5. Assuming void Means undefined

void functions return undefined at runtime, but the type void means "the return value should be ignored." A function explicitly returning undefined has return type undefined (more specific).

6. Not Enabling strictNullChecks

Without it, null and undefined are assignable to everything, which nullifies the type system's ability to catch null pointer errors.

Practice Questions

  1. What is the difference between any and unknown? any disables type checking entirely. unknown forces you to narrow the type before using it, making it the safer choice for values of unknown origin.

  2. When would you use a tuple instead of an array? When you have a fixed number of elements with specific types, like [string, number] for a name-age pair or [number, number] for coordinates.

  3. What does never represent as a return type? A function that never completes normally — it always throws an error or runs infinitely.

  4. Can you reassign a variable declared with const to a different type? No. const prevents reassignment entirely. With let, you can reassign but the type is fixed after initial inference.

Challenge: Write a function that accepts a string | number parameter, narrows it with typeof, and returns the length (if string) or the square (if number). Add proper return types for both branches.

FAQ

What is the difference between `Array` and `string[]`?

They are identical. string[] is the preferred syntax for simplicity. Array<string> uses the generic syntax and is useful in complex type expressions.

Why does `typeof null` return "object" in JavaScript?

This is a long-standing JavaScript bug from the first version. TypeScript's null type is separate and not affected by this.

Can I use `number` for large integers?

number is a 64-bit float, precise up to 2^53. For larger integers, use bigint (ES2020+): const big: bigint = 9007199254740991n;

What happens if I don't specify a type for a function parameter?

With strict: true, TypeScript infers any and reports an error (via noImplicitAny). You must provide a parameter type.

How do I create an empty typed array?

const items: string[] = []; or const items = [] as string[]; TypeScript infers the type from the annotation.

Mini Project: Type Catalog

Create a src/types-catalog.ts that demonstrates each basic type with real-world data:

// Types Catalog — demonstrates each basic type

// Primitives
const appName: string = "DodaTech Scanner";
const version: number = 3.1;
const isProduction: boolean = true;

// Arrays
const threatNames: string[] = ["Trojan.Generic", "Worm.AutoRun", "Adware.Bundle"];
const scanResults: boolean[] = [true, false, true, false];

// Tuples
const scanEntry: [Date, string, boolean] = [new Date(), "scan-001", true];
const coordinate: [x: number, y: number, z?: number] = [10, 20];

// Special types
let rawData: unknown = JSON.parse('{"name":"malware.exe"}');
if (typeof rawData === "object" && rawData !== null) {
  console.log("Valid JSON object received");
}

function reportError(msg: string): never {
  throw new Error(msg);
}

function logEvent(event: string): void {
  console.log(`[${new Date().toISOString()}] ${event}`);
}

// Display
console.log(`App: ${appName} v${version} (Production: ${isProduction})`);
console.log(`Threats found: ${threatNames.length}`);
logEvent("Type catalog completed");

Expected output:

App: DodaTech Scanner v3.1 (Production: true)
Threats found: 4
[2026-06-28T...] Type catalog completed

What's Next

Now that you know basic types, learn how to shape objects with interfaces:

Lesson Description
{{< ref "/programming-languages/typescript/02-installation-setup" >}} Review setup basics
{{< ref "/programming-languages/typescript/04-interfaces" >}} Object shapes with interfaces
{{< ref "/programming-languages/typescript/05-type-aliases" >}} Union, intersection, and literal types

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro