Type System Basics
🎯 Introduction
This article introduces the foundations of TypeScript's type system. You will learn to describe data structures with types and write safer, more maintainable code. Understanding basic types, arrays, tuples, special types, and type annotations helps you improve code quality in frontend projects.
🟢 Basic Types: string, number, boolean, null, undefined
TypeScript's most basic types correspond to familiar JavaScript types. They describe the kind of data a variable holds.
const myName: string = 'Ming';
const age: number = 25;
const isStudent: boolean = true;
const emptyValue: null = null;
const notAssigned: undefined = undefined;
- string represents text, such as names and addresses.
- number represents numbers, including integers and floating-point values.
- boolean has two possible values: true and false.
- null and undefined are special values: null represents an intentional absence of a value, while undefined represents a value that has not been defined.
Think of null as a box deliberately left empty, and undefined as a box that has not had anything put in it yet.
🟠 Arrays and Tuples
An array stores a collection of elements of the same type. A tuple describes an array with a fixed length whose elements can have different types.
// An array of numbers
const scores: number[] = [98, 87, 92];
// The generic syntax is also available
const names: Array<string> = ['Hong', 'Ming', 'Gang'];
// A tuple: fixed length, with a type for each position
const user: [string, number] = ['Ming', 25];
An array is a sequence of values of the same type. A tuple is useful for records, such as user information with a name string in the first position and an age number in the second.
🔵 any、unknown、void、never
These types have special roles in TypeScript.
let anything: any = 123;
anything = 'Now a string';
anything = true; // any accepts values of any type
let notSure: unknown = 10;
notSure = 'hello'; // unknown accepts any value, but restricts operations on it
function sayHello(): void {
console.log('Hello');
}
function throwError(): never {
throw new Error('Something went wrong!');
}
- any disables type checking for a value, giving up type safety. Use it sparingly.
- unknown represents an unknown type. It is safer than any because you must check the type before using the value.
- void is typically the return type of a function that does not return a value.
- never represents values that cannot occur. It is often used for functions that throw an exception or loop forever instead of returning.
As an analogy, any is a blank sheet of paper you can draw anything on. unknown is a covered sheet: you must uncover it and see what is there before working with it.
⚙️ Function Parameter and Return Types
Functions are central to frontend development. Annotating parameter and return types makes their contracts clearer and helps prevent runtime errors.
function add(x: number, y: number): number {
return x + y;
}
Here, both parameters of add, x and y, have type number, and the return value is also a number. Passing a value of another type produces a compiler error.
🟣 Type Annotations vs. Type Inference
TypeScript can infer variable types automatically, but you can also provide explicit type annotations.
// Type annotation: explicitly specify the type
const count: number = 10;
// Type inference: TypeScript determines the type without an annotation
const message = 'Hello, TS'; // Inferred as string
// Function parameter type annotations
function sum(a: number, b: number): number {
return a + b;
}
- A type annotation explicitly tells the compiler a variable's type.
- Type inference lets the compiler determine a type from a variable's initial value.
Think of TypeScript as an assistant that works out variable types for you. When it cannot determine the type accurately, provide the information explicitly.
🟤 Introduction to Type Aliases (type) and Interfaces (interface)
What Is a Type Alias?
A type alias uses the type keyword to give a type a name. It can name a primitive type, union, tuple, object type, and more.
type UserID = string;
type User = {
id: UserID;
name: string;
age?: number;
};
What Is an Interface?
An interface defines an object's structure using the interface keyword. It is particularly useful for defining contracts in object-oriented code.
interface User {
id: string;
name: string;
age?: number;
}
Interfaces also support extension and declaration merging, making them useful for extensible structures.
Scenario 1: Prefer interface for Object Structures
interface User {
id: number;
name: string;
age?: number;
}
Why use interface:
- It clearly communicates that you are describing an object structure;
- It supports extension and declaration merging;
- It is convenient for others to extend, especially in libraries and declaration files.
Scenario 2: Use type to Name a Union
type Status = 'loading' | 'success' | 'error';
Why use type:
- An
interfacecannot directly define a union; - A
typealias can describe combinations of string literal types and allowed values.
Scenario 3: Use type to Name a Tuple
type Point = [number, number];
Why use type:
- A
typealias can directly name a tuple such as[x, y]; - An
interfacedoes not provide the same direct tuple syntax for ordered arrays of a fixed length.
Scenario 5: Use interface for Extension or Declaration Merging
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
Alternatively, use declaration merging:
interface User {
id: number;
}
interface User {
name: string;
}
// After merging, equivalent to: { id: number; name: string }
A type alias cannot merge declarations this way; duplicate declarations produce an error.
What Is an Enum (enum)?
An enum defines a set of named constants. It groups related values together and makes code clearer. There are three main kinds of enums.
Numeric Enums
Numeric enums are the most common form. Members are numbered starting at 0 by default. You can also set an initial value explicitly, with subsequent members incrementing from it.
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
console.log(Direction.Left); // 2
String Enums
String enum members require explicit values because they do not auto-increment. They are useful when you want readable values that correspond clearly to their names.
enum Role {
Admin = 'ADMIN',
User = 'USER',
Guest = 'GUEST',
}
Heterogeneous Enums (Mixed Numbers and Strings)
Heterogeneous enums contain both numeric and string members. They are generally discouraged because they make code less consistent and harder to read.
enum Result {
Success = 1,
Fail = 'FAIL',
}
❓ Questions and Answers
Q1: What is the difference between any and unknown in TypeScript?
any disables type checking and permits unrestricted operations. unknown is safer because you must check the type before using the value.
Q2: When should I use a tuple instead of an array?
Use a tuple when the data has a fixed length and each position has a specific type, as with a user information record.
Q3: What is the main difference between interfaces and type aliases?
Interfaces support extension and implementation, making them useful for object-oriented design. Type aliases are more flexible and can also name types such as unions.
🧪 Practice Exercises
Exercise 1: Write a type alias for a product object with a name (string), price (number), and availability flag (boolean).
type Product = {
// Write your code here
};
const phone: Product = {
// Initialize the phone object here
};
Exercise 2: Write a function that accepts a tuple containing a person's name and age, and returns a string introducing that person.
function introduce(person: [string, number]): string {
// Write your code here
}
console.log(introduce(['Ming', 25])); // Example output: I am Ming, and I am 25 years old.
🎉 You now know TypeScript's basic types, arrays and tuples, special types, type annotations and inference, and the basics of type aliases and interfaces! Keep practicing to strengthen your frontend development skills.
Introduction to TypeScript
Learn what TypeScript is, how it relates to JavaScript, why it is useful, and how to get started and integrate it with Webpack.
Combining Types and Using Type Guards
Learn the differences between unions and intersections, how to use type assertions correctly, and common type guard techniques in TypeScript.
