Series: TypeScript from Basics to Advanced
Part: 2 — TypeScript Basic Types
Level: Beginner
Reading time: 10–12 minutes
Introduction
In the previous article, we learned what TypeScript is, how it differs from JavaScript, and how TypeScript uses static typing to catch errors during development.
Now it's time to learn one of the most important parts of TypeScript:
Types.
Types tell TypeScript what kind of value a variable, function, parameter, or object is expected to contain.
For example:
let username: string = "Sundar";
let age: number = 25;
let isDeveloper: boolean = true;
Here:
-
usernameis astring -
ageis anumber -
isDeveloperis aboolean
But TypeScript has more types than these three.
In this article, we'll understand the most important basic types:
string
number
boolean
null
undefined
any
unknown
never
void
We'll also see when to use them and when to avoid them.
1. String
The string type represents text.
let username: string = "Sundar";
You can use:
let firstName: string = "Sundar";
let lastName: string = "Rao";
You can also use template literals:
let message: string = `Hello ${firstName}`;
If you try to assign a number:
let username: string = 100;
TypeScript reports an error because 100 is a number, not a string.
TypeScript also infers strings
You don't always need to explicitly write string.
let username = "Sundar";
TypeScript automatically understands:
username → string
So this is usually unnecessary:
let username: string = "Sundar";
when the type is already obvious.
2. Number
The number type represents numeric values.
let age: number = 25;
let price: number = 999.99;
let temperature: number = -10;
JavaScript doesn't have separate int, float, or double types.
So all of these are:
number
For example:
let integer: number = 100;
let decimal: number = 10.5;
Both are number.
You can also use:
let hexadecimal: number = 0xff;
let binary: number = 0b1010;
3. Boolean
The boolean type represents either:
true
or:
false
Example:
let isLoggedIn: boolean = true;
let isAdmin: boolean = false;
A common example in applications is authentication:
const isAuthenticated: boolean = true;
if (isAuthenticated) {
console.log("User is logged in");
}
You cannot assign a string:
let isAdmin: boolean = "yes";
TypeScript will report an error.
4. Null
null represents an intentional absence of a value.
let selectedUser: null = null;
A more realistic example is a value that may or may not exist.
With strict TypeScript settings, you would typically write:
let selectedUser: User | null = null;
This means:
selectedUsercan either contain aUseror benull.
For example:
interface User {
id: number;
name: string;
}
let selectedUser: User | null = null;
Later:
selectedUser = {
id: 1,
name: "Sundar"
};
This pattern is extremely common in React applications.
5. Undefined
undefined generally means that a value has not been assigned.
let username: string | undefined;
Initially:
username → undefined
You can later assign:
username = "Sundar";
Optional properties can also result in undefined.
For example:
interface User {
name: string;
email?: string;
}
The email property is optional.
Therefore:
const user: User = {
name: "Sundar"
};
user.email may be undefined.
6. The any Type
Now we reach one of the most misunderstood TypeScript types:
any
any essentially tells TypeScript:
Don't check this value's type.
For example:
let value: any = "Hello";
value = 100;
value = true;
value = {
name: "Sundar"
};
All of these are allowed.
You can even do:
let value: any = "Hello";
value.toUpperCase();
And:
value.someUnknownMethod();
TypeScript won't complain.
That's powerful—but dangerous.
Why any Can Be Dangerous
Consider:
let username: any = "Sundar";
username.toUpperCase();
This works.
But:
username = 100;
username.toUpperCase();
Now the code can fail at runtime.
The problem is that we've effectively disabled TypeScript's type checking for that value.
Therefore:
Avoid
anyunless you have a specific reason to use it.
A common beginner mistake is to add any whenever TypeScript reports an error.
For example:
const user: any = response.data;
This may make the error disappear, but it also removes useful type safety.
A better solution is usually to properly define the type.
7. The unknown Type
unknown is similar to any in one important way:
You don't know what type of value it contains.
But unlike any, TypeScript doesn't allow you to use the value without checking its type first.
Example:
let value: unknown;
value = "Hello";
value = 100;
value = true;
All of these assignments are allowed.
But this isn't:
value.toUpperCase();
TypeScript reports an error because it doesn't know whether value is a string.
You need to check first:
if (typeof value === "string") {
console.log(value.toUpperCase());
}
Now TypeScript knows that inside the if block:
value → string
This makes unknown much safer than any.
any vs unknown
This distinction is extremely important.
any
let value: any = "Hello";
value.toUpperCase();
value.someMethod();
value.randomProperty;
TypeScript essentially trusts you.
unknown
let value: unknown = "Hello";
You must check the type:
if (typeof value === "string") {
value.toUpperCase();
}
Think about it this way:
any
↓
"Trust me, TypeScript."
unknown
↓
"Prove to me what this value is."
When dealing with data whose type you genuinely don't know, prefer unknown over any.
8. The void Type
void is commonly used as the return type of a function that doesn't return a useful value.
Example:
function logMessage(message: string): void {
console.log(message);
}
The function performs an action but doesn't return a value.
Another example:
function sendEmail(): void {
console.log("Email sent");
}
You will frequently see void when typing callbacks and functions.
9. The never Type
never represents a value that never occurs.
It is commonly used for functions that never successfully finish.
For example, a function that always throws an error:
function throwError(message: string): never {
throw new Error(message);
}
The function doesn't return a value.
Instead, it always throws.
Another example is an infinite loop:
function infiniteLoop(): never {
while (true) {
// continues forever
}
}
never is also useful in advanced TypeScript patterns, particularly exhaustive checking.
For example:
type Status = "success" | "error";
function handleStatus(status: Status) {
switch (status) {
case "success":
return "Done";
case "error":
return "Something went wrong";
default:
return assertNever(status);
}
}
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
We'll explore this pattern later when we discuss advanced TypeScript.
10. Type Inference
As we saw in the previous article, TypeScript can often determine types automatically.
let username = "Sundar";
let age = 25;
let isDeveloper = true;
TypeScript infers:
username → string
age → number
isDeveloper → boolean
You don't need to explicitly annotate every variable.
This:
const age = 25;
is generally preferable to:
const age: number = 25;
because the type is obvious.
When Should You Add Type Annotations?
Type inference is useful, but explicit annotations are valuable when they communicate intent or describe boundaries.
For example:
function calculateSalary(
salary: number,
bonus: number
): number {
return salary + bonus;
}
Here, the function's contract is important.
Another example:
let selectedUser: User | null = null;
The annotation communicates that the variable is intentionally allowed to be either a User or null.
A Practical Example
Let's combine several types.
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}
const user: User = {
id: 1,
name: "Sundar",
email: "sundar@example.com",
isActive: true
};
Now imagine we have a currently selected user:
let selectedUser: User | null = null;
And an API response:
let apiData: unknown;
We might check it before using it:
if (typeof apiData === "object" && apiData !== null) {
console.log("Received an object");
}
This is a much safer approach than:
let apiData: any;
Basic Types Cheat Sheet
TypePurposeExamplestringText"Sundar"numberNumbers100booleanTrue/falsetruenullIntentional absencenullundefinedMissing/unassigned valueundefinedanyDisables type checkinganyunknownUnknown but type-safe valueunknownvoidFunction returns no useful valuevoidneverValue never occurs/returnsnever
Common Beginner Mistakes
Mistake 1: Using any Everywhere
Avoid:
const user: any = response.data;
Prefer defining the actual type:
const user: User = response.data;
Or use unknown when the data genuinely isn't known yet.
Mistake 2: Explicitly Typing Everything
You don't need:
const name: string = "Sundar";
const age: number = 25;
const active: boolean = true;
This is often enough:
const name = "Sundar";
const age = 25;
const active = true;
Let TypeScript infer obvious types.
Mistake 3: Confusing void and never
A function returning void finishes normally:
function log(): void {
console.log("Hello");
}
A function returning never doesn't successfully finish:
function fail(): never {
throw new Error("Failed");
}
Recommended Rules
When starting with TypeScript, these rules will keep your code safer:
Rule 1
Use explicit types when they improve clarity.
Rule 2
Let TypeScript infer obvious types.
Rule 3
Avoid any whenever possible.
Rule 4
Prefer unknown when the type is genuinely unknown.
Rule 5
Use union types when a value can legitimately have multiple types.
let id: string | number;
Rule 6
Enable strict type checking in your projects.
We'll cover strict and tsconfig.json later in this series.
Final Takeaway
The basic TypeScript types form the foundation of the entire type system.
The most important ones to remember are:
string
number
boolean
for everyday values,
null
undefined
for missing or absent values,
unknown
for values whose type isn't known yet,
void
for functions that don't return a useful value,
and:
never
for situations where a value can never occur or a function never successfully returns.
Most importantly, remember this:
Don't use
anyjust to make a TypeScript error disappear.
The purpose of TypeScript is to give you useful type safety. Removing the type system with any defeats much of that purpose.