Tutorials / TypeScript: Beginner to Advanced / Basic types: primitives, arrays, tuples, any and unknown

Basic types: primitives, arrays, tuples, any and unknown

15 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

Type annotations and inference

You add a type after a name with a colon. This is a type annotation.

const userName: string = "Sara";
const age: number = 28;
const isActive: boolean = true;

let score: number = 10;
score = 20;
// score = "high";   // Error: Type 'string' is not assignable to type 'number'

console.log(userName, age, isActive, score);

You often do not have to write the type, because TypeScript works it out from the value. This is type inference:

const city = "Lahore";      // type is "Lahore" (a literal, because it is const)
let count = 0;              // type is number
let flag = true;            // type is boolean

count = count + 1;          // fine
// flag = "yes";            // Error

My rule is to let inference do the work for local variables, and to write the types explicitly on function parameters and on the shape of data that crosses boundaries (API results, function returns that are exported). That gives you most of the safety with the least noise.

The primitive types

TypeExample values
string"hello", 'hi', template
number42, 3.14, NaN. Whole numbers and decimals are both number
booleantrue, false
bigint123n
symbolSymbol("id")
null and undefinedThe empty values. They have their own types

Use the lower case names. Types such as String and Number with a capital letter refer to wrapper objects and you almost never want them.

Arrays

Two equivalent ways to write an array type:

const scores: number[] = [90, 85, 70];
const names: Array<string> = ["Ali", "Sara"];

scores.push(100);
// scores.push("a");     // Error

const first = scores[0];   // number
console.log(first, names);

I use number[] for simple cases and Array<...> when the element type is long. An empty array needs an annotation or TypeScript infers a poor type:

const items: string[] = [];
items.push("one");
console.log(items);

Tuples

A tuple is an array with a fixed length where each position has its own type:

const point: [number, number] = [10, 20];
const entry: [string, number] = ["age", 28];

const [key, value] = entry;
console.log(key.toUpperCase(), value + 1, point[0]);

// const bad: [string, number] = [28, "age"];   // Error

Tuples are useful for returning two or three related values from a function, much like destructured pairs in JavaScript. You can also name the positions for readability: type Range = [start: number, end: number].

any: the escape hatch

The any type switches off checking. A value of type any can be used as anything, and TypeScript will not complain:

let data: any = "hello";
data = 42;
data = { a: 1 };
console.log(data.something.deep);   // compiles; at runtime, undefined

That last line compiles, and crashes only when data.something is undefined and you read .deep. With any, you are back to plain JavaScript, and any spreads: a value derived from an any is also any. Use it only as a last resort, for instance for a quick prototype or while migrating old code.

unknown: the safe version

When you truly do not know what a value is, use unknown. You can put anything into it, but you must check the type before using it.

function describe(value: unknown): string {
  if (typeof value === "string") {
    return `text of length ${value.length}`;
  }
  if (typeof value === "number") {
    return `number ${value.toFixed(1)}`;
  }
  if (Array.isArray(value)) {
    return `array with ${value.length} items`;
  }
  return "something else";
}

console.log(describe("hello"));   // text of length 5
console.log(describe(3.14159));   // number 3.1
console.log(describe([1, 2]));    // array with 2 items
console.log(describe(null));      // something else

Inside each if, TypeScript knows the narrower type. This is called narrowing, and it is the topic of a later lesson. The point is that unknown forces you to prove what the value is before you use it. For anything that comes from outside your program, such as JSON.parse, user input or a network response, unknown is the honest type.

void, never and object

  • void is the return type of a function that returns nothing.
  • never is the type of something that cannot happen, for example a function that always throws.
  • object means any non-primitive value. In practice, you describe the shape instead.
function log(message: string): void {
  console.log(message);
}

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

log("done");

Type assertions

Sometimes you know more than the compiler. An assertion with as tells it to trust you:

const input = { value: "42" } as { value: string };
const el = document.querySelector("#price") as HTMLInputElement | null;
console.log(input.value, el?.value);

An assertion does not change the value or check anything at runtime. If you are wrong, you get a crash later. Prefer narrowing with a real check, and use as sparingly.

Common mistakes

  • **Using any to silence an error.** Try unknown and a check instead.
  • Capital letter types. Write string, not String.
  • Declaring an empty array without a type. In strict mode const a = [] starts as an evolving type that can surprise you. Annotate: const a: string[] = [].
  • Over-annotating. const x: number = 5 adds nothing.
  • **Trusting as.** It is a promise to the compiler, and the compiler cannot verify it.
  • **Mixing up null and undefined.** They are separate types, and strict mode makes you handle both.

Try it yourself

  1. Declare variables of each primitive type and try to assign the wrong type to one of them.
  2. Create a tuple type for [string, number, boolean] and destructure it.
  3. Write a function safeLength(value: unknown): number that returns the length for strings and arrays and 0 for anything else.
  4. Replace an any in one of your old snippets with unknown and fix the errors that appear.
typescript
const userName: string = "Sara";
const age: number = 28;
const isActive: boolean = true;

let score: number = 10;
score = 20;
// score = "high";   // Error: Type 'string' is not assignable to type 'number'

console.log(userName, age, isActive, score);

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account