Reference · library-grade patterns
Five real-world shapes you'll meet in @types/…. For each: what to look
for, and how to read it without drowning. Find the inferred input; treat the rest as defaults.
Find the one parameter inferred from your call; the rest default off it. Trace that parameter to its one meaningful use, not every layer.
declare function useQuery<
TQueryFnData = unknown, // ← inferred from queryFn's return type
TError = DefaultError,
TData = TQueryFnData, // ← defaults off TQueryFnData
TQueryKey extends QueryKey = QueryKey
>(options: UndefinedInitialDataOptions<...>): UseQueryResult<TData, TError>;
// the field that PRODUCES the inference, deep in the layers:
type QueryFunction<T> = (ctx: ...) => T | Promise<T>; // T = return type
Layers (QueryOptions → … → UndefinedInitialDataOptions) just forward
the same params and add fields. TData ≠ TQueryFnData only when you pass
select.
A method returningClass<TOld & New>instead of plainthisis accumulating. Read the return type; the body is justreturn this.
class TypeSafeStringMap<TMap extends Record<string,string> = {}> {
get(key: keyof TMap): string { ... } // only keys set so far
set<K extends string>(key: K, value: string)
: TypeSafeStringMap<TMap & Record<K, string>> { return this; }
}
// new TypeSafeStringMap().set("a","1").set("b","2")
// → TMap = { a: string } & { b: string }; get("c") errors
Phantom = compile-time only. TMap never appears in emitted JS.
Base type&an object with a never-assigned marker (__brand, aunique symbol) = a brand. It fakes nominal typing in a structural system.
type UserId = string & { readonly __brand: 'UserId' };
function toUserId(s: string): UserId { /* validate */ return s as UserId; }
const raw: string = "x";
getUser(raw); // ❌ missing __brand → not a UserId
getUser(toUserId(raw)); // ✅ minted through the one sanctioned cast
The brand is a promise the value passed toUserId, not a runtime check.
| type | read as | width |
|---|---|---|
| ReactNode | anything renderable | widest — strings, arrays, null, elements |
| ReactElement | one element object | narrow — a single element |
| JSX.Element | ReactElement, loose generics | narrow — what JSX evaluates to |
children → ReactNode (wide slot). Component return type →
ReactElement / JSX.Element (narrow). Grab props without an export:
type Props = ComponentProps<typeof ComponentA>; // typeof = value type → extract props
fn<T>()(arg)= curry to fixTfirst, then infer fromarg. Needed whenTis invariant (in both input and output positions) so single-call inference yieldsunknown.
const useStore = create<BearState>()((set) => ({ // () pins T; then creator is checked
bears: 0,
increase: (by) => set((s) => ({ bears: s.bears + by })),
}));
// StateCreator<T> = (set, get) => T — with T fixed, set/get/return all resolve
extends ? :, infer, mapped,
template-literal, intersection (Module 3).