Recursive conditional types là kiểu điều kiện tự gọi lại chính nó, cho phép duyệt qua các nested types ở mọi cấp độ, ví dụ: type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T sẽ biến tất cả properties thành optional ở mọi tầng lồng nhau.
- TypeScript giới hạn độ sâu đệ quy (thường khoảng 50 levels) để tránh infinite loop trong quá trình type checking.
- Kỹ thuật này rất hữu ích để xây dựng các utility types phức tạp như DeepReadonly, DeepRequired, hay Flatten để biến đổi cấu trúc dữ liệu lồng nhau một cách type-safe.
Recursive conditional types are conditional types that call themselves, allowing traversal through nested types at every level.
- For example:
type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : Tmakes all properties optional at every nesting level. - TypeScript limits recursion depth (typically around 50 levels) to prevent infinite loops during type checking.
- This technique is very useful for building complex utility types like DeepReadonly, DeepRequired, or Flatten for type-safely transforming nested data structures.