Skip to content

Instantly share code, notes, and snippets.

@overthemike
Last active April 25, 2025 04:32
Show Gist options
  • Save overthemike/acb9eed71e27cb384043ca2b58b2b668 to your computer and use it in GitHub Desktop.
Save overthemike/acb9eed71e27cb384043ca2b58b2b668 to your computer and use it in GitHub Desktop.
Initializing state without known values
// Descriminated Union
type DataState<T> =
| { status: 'loading' }
| { status: 'error', error: Error }
| { status: 'success', data: T }
interface User {
name: string
age: number
}
const initialState: DataState<User> = { status: 'loading' };
// and then later after state is loaded: { status: 'success', data: state }
// Initializing with empty values with a generic
const EMPTY = Symbol('Empty Value') // initial empty value
export type Initial<T> = {
[K in keyof T]: Initial<T[K]> | T[K] | typeof EMPTY
}
interface User {
name: string
age: number
}
const initialState: Initial<User> = {
name: EMPTY,
age: EMPTY
}
// Lazy Factory
interface UserState {
name: string;
age: number;
}
function createInitialState<T>(factory: () => T): () => T {
let state: T | undefined;
return () => {
if (state === undefined) {
state = factory();
}
return state;
};
}
const getUserState = createInitialState<UserState>(() => {
// Compute or fetch initial state when first needed
return { name: "Unknown", age: 0 };
});
// this one can cause type issues "cannot set foo to 'null'" bla bla
interface User {
name: string | null
age: number | null
}
const initialState = {
name: null,
age: null
}
interface User {
name?: string
age?: number
}
const initialState: User = {}
interface User {
name: string
age: string
}
const initialState: Partial<User> = {}
// not a fan of this one as the 'default' values can be legit values
interface UserState {
name: string
age: number
}
const initialState: UserState = {
name: '',
age: -1
};
interface User {
name: string
age: number
}
const initialState = {} as User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment