Category: type Since: 1.0.0 Tags: type, undefined, union, optional, uninitialized
MaybeUndefined
Represents a value that may be undefined.
Usage
import type { MaybeUndefined } from "@petr-ptacek/js-core";
function getConfig(key: string): MaybeUndefined<string> {
return process.env[key]; // undefined if not set
}
const apiUrl: MaybeUndefined<string> = getConfig("API_URL");
// Type: string | undefinedWhy This Type Exists
In JavaScript/TypeScript, values are undefined when they haven't been initialized or when accessing non-existent object properties. MaybeUndefined<T> provides semantic clarity for values that might not exist yet or might be missing, making the optional nature explicit in type signatures.
Type Declaration
type MaybeUndefined<T> = T | undefined;Type Parameters
<T>: The base type that may also beundefined.
When To Use
Use MaybeUndefined<T> when:
- working with optional object properties
- handling uninitialized variables
- dealing with array methods that might not return a value (
find,pop, etc.) - representing values that might not be provided
- working with environment variables or configuration
// Configuration example
interface AppConfig {
apiUrl: string;
timeout: number;
debugMode: MaybeUndefined<boolean>; // optional config
logLevel: MaybeUndefined<string>; // might not be configured
}
const config: AppConfig = {
apiUrl: "https://api.example.com",
timeout: 5000,
debugMode: process.env.DEBUG === "true" ? true : undefined,
logLevel: process.env.LOG_LEVEL, // undefined if not set
};
// Array operations
function findUser(users: Array<{ id: string }>, id: string): MaybeUndefined<{ id: string }> {
return users.find((user) => user.id === id);
}
const foundUser = findUser(users, "123");
if (foundUser !== undefined) {
console.log("Found:", foundUser.id);
}When Not To Use
Avoid when:
- you need to represent intentional absence (use
MaybeNull<T>orT | null) - you need both
nullandundefined(useMaybeNullable<T>) - the value should always be defined (use
Tdirectly) - you specifically need
nullfor API consistency
Design Notes
This type follows the semantic distinction where:
undefinedrepresents uninitialized, missing, or non-existent valuesnullrepresents intentional absence of a valueMaybeUndefined<T>specifically handles theundefinedcase
The type is equivalent to T | undefined and is often used with optional properties and parameters.
Summary
MaybeUndefined<T> provides semantic clarity for values that might be uninitialized or missing, making optional types explicit and improving type safety in scenarios where undefined indicates the absence of initialization or assignment.