TypeScript key of Nested Object

Setup

type NestedKeyOf<ObjectType extends object> = {
	[Key in keyof ObjectType]: ObjectType[Key] extends object
		? NestedKeyOf<ObjectType[Key]>
		: Key;
}[keyof ObjectType];

Example

// Define main object
const PERMISSION = {
	USER: {
		UPDATE: 'CAN_UPDATE_USER',
		GET: 'CAN_GET_USER',
	},
};

// Define types
type UserPermissionObject = keyof typeof PERMISSION;
type UserPermissionAction = NestedKeyOf<
	typeof PERMISSION
>;
<-- Back to Posts