What is a type in TypeScript?
1. What is type
In TypeScript, the
typekeyword is used to create a custom type
- that is, a new name for a combination of existing types.
It is similar to a "label" or "type alias". TypeScript does not add a new object to memory - it is simply a description of the data structure for compile-time checking.
Example 1: a simple type (type alias)
type UserName = string;
const name: UserName = "Tim";Here
UserNameis just an alias for thestringtype. Types help make code self-documenting.
Example 2: an object type
type User = {
id: number;
name: string;
isAdmin?: boolean; // optional property
};
const user: User = {
id: 1,
name: "Tim",
};TypeScript checks that
usercontains the required fields and correct types.
2. type ≠ a variable
Types do not exist at runtime - they are needed only by the compiler for checking and hints.
type Product = { id: number; title: string };After compiling to JS - no type Product will remain.
3. Types can be unioned and combined
This is where type shows its full power.
Union Types
A value can be one of several types:
type Status = "loading" | "success" | "error";
let current: Status = "loading"; // OK
current = "fail"; // Error: no such value existsIntersection Types
Combines several types into one "complex" type.
type Person = { name: string };
type Employee = { company: string };
type Worker = Person & Employee;
const w: Worker = { name: "Tim", company: "Acme Inc" }; // OKFunction types
type Sum = (a: number, b: number) => number;
const add: Sum = (x, y) => x + y;Array and tuple types
type Numbers = number[];
type Point = [number, number]; // a tuple4. The difference between type and interface
| Capability | interface | type |
|---|---|---|
| Describing objects | Yes | Yes |
Extension (extends) | Yes | Yes (&) |
| Declaration merging | Yes | No |
| Union and primitives | No | Yes |
| Tuple and Function | No | Yes |
Implementation by a class (implements) | Yes | Yes |
Practical rule:
- Use
interfacefor objects, structures, and classes- Use
typefor combinations, unions, and aliases
5. Example - combining type and interface
interface User {
id: number;
name: string;
}
type Admin = User & { role: "admin" };
const tim: Admin = { id: 1, name: "Tim", role: "admin" };Here
typeis used to extend the interface through an intersection (&).
6. Why type is needed at all
- Makes types reusable
- Simplifies reading and maintaining code
- Lets you combine and assemble complex structures
- Helps the IDE offer hints and check types
- Makes code self-documenting
Summary
typeis TypeScript's mechanism for creating new custom types (aliases) in order to describe the shape of data and to union and combine types.It is used for:
- unions (
|),- intersections (
&),- functions, tuples, and primitives,
- as well as for code convenience and readability.
type= "a flexible constructor for describing data".
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.