From 12f4cf8a107e89645fe65833a359a53f36e01103 Mon Sep 17 00:00:00 2001 From: Lenz Weber Date: Tue, 20 Oct 2020 21:31:16 +0200 Subject: [PATCH] fix: skip ReadonlyMap and ReadonlySet types when not available (#653). Fixes #624 --- src/types/types-external.ts | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/types/types-external.ts b/src/types/types-external.ts index 22947e1e..0dbd8f86 100644 --- a/src/types/types-external.ts +++ b/src/types/types-external.ts @@ -17,19 +17,36 @@ type AtomicObject = | Number | String +/** + * If the lib "ES2105.collections" is not included in tsconfig.json, + * types like ReadonlyArray, WeakMap etc. fall back to `any` (specified nowhere) + * or `{}` (from the node types), in both cases entering an infite recursion in + * pattern matching type mappings + * This type can be used to cast these types to `void` in these cases. + */ +export type IfAvailable = + // fallback if any + true | false extends (T extends never + ? true + : false) + ? Fallback // fallback if empty type + : keyof T extends never + ? Fallback // original type + : T + /** * These should also never be mapped but must be tested after regular Map and * Set */ -type WeakReferences = WeakMap | WeakSet +type WeakReferences = IfAvailable> | IfAvailable> export type WritableDraft = {-readonly [K in keyof T]: Draft} export type Draft = T extends AtomicObject ? T - : T extends ReadonlyMap // Map extends ReadonlyMap + : T extends IfAvailable> // Map extends ReadonlyMap ? Map, Draft> - : T extends ReadonlySet // Set extends ReadonlySet + : T extends IfAvailable> // Set extends ReadonlySet ? Set> : T extends WeakReferences ? T @@ -40,9 +57,9 @@ export type Draft = T extends AtomicObject /** Convert a mutable type into a readonly type */ export type Immutable = T extends AtomicObject ? T - : T extends ReadonlyMap // Map extends ReadonlyMap + : T extends IfAvailable> // Map extends ReadonlyMap ? ReadonlyMap, Immutable> - : T extends ReadonlySet // Set extends ReadonlySet + : T extends IfAvailable> // Set extends ReadonlySet ? ReadonlySet> : T extends WeakReferences ? T