Optional

2 snippets across 2 stacks — Python, TypeScript

Also written as all optional

PYPython

typing Module Essentials

PY · Common Standard Library
syntax
from typing import Optional, Union, TypeVar, Generic
example
from typing import TypeVar, Generic

T = TypeVar("T")

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

stack = Stack[int]()
stack.push(42)
print(stack.pop())
output
42

Note Since 3.10, use X | Y instead of Union[X, Y]. Since 3.12, use the type parameter syntax: class Stack[T]: instead of TypeVar + Generic.

TSTypeScript

Partial<T>

TS · Utility Types
syntax
type Result = Partial<OriginalType>;
example
interface Settings {
  theme: "light" | "dark";
  fontSize: number;
  notifications: boolean;
}

function updateSettings(current: Settings, changes: Partial<Settings>): Settings {
  return { ...current, ...changes };
}

const updated = updateSettings(
  { theme: "light", fontSize: 14, notifications: true },
  { fontSize: 16 } // only need to pass what changed
);
output
// Partial<Settings> makes all properties optional

Note Partial only operates one level deep. Nested objects keep their original required types. For deep partial, you need a custom recursive type or a library utility.