Skip to content

Instantly share code, notes, and snippets.

@graffhyrum
Created March 14, 2025 23:40
Show Gist options
  • Save graffhyrum/0c6317e4b9465e95010ae92c040339f5 to your computer and use it in GitHub Desktop.
Save graffhyrum/0c6317e4b9465e95010ae92c040339f5 to your computer and use it in GitHub Desktop.
/**
* Creates a typed key-value pair object to work around TypeScript issue #13948.
* This function preserves the literal type of the key in the resulting object type.
*
* @see [source](https://github.com/microsoft/TypeScript/issues/13948#issuecomment-1333159066)
*
* @example
* const obj = createTypedKeyValue('userId', 123);
* // obj has type: { userId: number } with literal key preservation
*
* @template K - The key type (must be a valid property key: string, number, or symbol)
* @template V - The value type
* @param key - The object property key
* @param value - The value to associate with the key
* @returns A strongly-typed object with the key-value pair
*/
export function createTypedKeyValue<const K extends PropertyKey, V>(
key: K,
value: V,
): {[P in K]: {[Q in P]: V}}[K] {
return {[key]: value} as any
}
/**
* Type utility that represents a key-value pair with preserved literal key types.
* Used as part of the TypeScript workaround for issue #13948.
*
* @template K - The key type (must be a valid property key: string, number, or symbol)
* @template V - The value type
*/
export type TypedKeyValue<K extends PropertyKey, V> = {
[P in K]: {[Q in P]: V}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment