Basic Types: Null, Undefined, Void, Never
TypeScript has several special types that represent the absence of values or specific scenarios. These types are null, undefined, void, and never.
The null type
The null type represents the intentional absence of a value. It's a value you can assign to a variable:
let user: string | null = null;
let data: number | null = null;
In TypeScript, null is its own type. However, you typically use it in combination with other types using a union type (we cover union types in detail later):
let name: string | null = null;
name = "Marge"; // Can be assigned a string
name = null; // Can be assigned null
The undefined type
The undefined type is for when a variable has not yet been assigned a value:
let username: string | undefined;
let age: number | undefined = undefined;
Like null, undefined is often used in union types:
let email: string | undefined = undefined;
email = "[email protected]"; // Can be assigned a string
Null vs undefined
While null and undefined are similar, they have different meanings:
null: Intentionally set to no valueundefined: Not set yet, or a value doesn't yet exist
// null - explicitly set to no value
let user: string | null = null;
// undefined - no value currently set
let username: string | undefined;
These types can be handled using conditional statements such as if:
Loading code...
function welcome(name: string | null | undefined): string {
if (name === null || name === undefined) {
return "Hello, Guest!";
}
return `Hello, ${name}!`;
}
console.log(welcome("Homer")); // "Hello, Homer!"
console.log(welcome(undefined)); // "Hello, Guest!"
console.log(welcome(null)); // "Hello, Guest!"
Optional properties and undefined
In TypeScript, optional properties can be undefined. The ? operator marks a property as optional, meaning it doesn't have to be provided when creating an object:
interface User {
name: string;
email?: string; // Optional - can be string or undefined
}
let user: User = {
name: "Homer"
// email is undefined here
};
Understanding the ? operator
The ? operator after a property name makes that property optional. This is shorthand for property: type | undefined. When a property is optional, you can:
- Include it when creating an object
- Omit it entirely (it will be
undefined)
Loading code...
interface User {
name: string;
email?: string; // Same as: email: string | undefined
age?: number; // Same as: age: number | undefined
}
let user1: User = {
name: "Bart",
email: "[email protected]" // Optional property included
};
let user2: User = {
name: "Maggie"
// email is omitted - it's undefined
};
console.log(user1); // { "name": "Bart", "email": "[email protected]" }
console.log(user2); // { "name": "Maggie" }
console.log(user2.email); // undefined
Accessing optional properties
As optional properties might be undefined, you need to check they are available before using them:
function sendEmail(user: User): void {
if (user.email) {
console.log(`Sending email to ${user.email}`);
} else {
console.log("No email address available");
}
}
The void type
The above function example uses the type of void. This is used to indicate that a function does not return a value. If you try to return a value from a function typed as void, TypeScript will show an error:
Loading code...
function logError(error: string): void {
return error; // Error: Type 'string' is not assignable to type 'void'
}
When to use void
Use void when a function performs an action but does not return anything useful/required:
function updateTitle(): void {
document.getElementById('title')!.innerText = "TypeScript void";
}
function saveData(): void {
localStorage.setItem('data', JSON.stringify({}));
}
The never type
The never type represents values that will never occur. It's used for functions that never return or always throw an error:
function logError(message: string): never {
throw new Error(message);
// This function never returns normally
}
function runForever(): never {
while (true) {
// Never exits
}
}
Summary
null: The absence of a valueundefined: Value not set or does not yet existvoid: Function doesn't return a valuenever: Value that will never occur (e.g. function never returns)
Special types can help TypeScript understand your code's behavior and catch potential errors. In the next lesson, we'll explore arrays and tuples, used to work with collections of values.