From 836ec1998e6904e8d160cf2a01b717a9470795c8 Mon Sep 17 00:00:00 2001 From: Matthias Kunnen Date: Wed, 27 Jan 2021 15:01:13 +0000 Subject: [PATCH] Store resolved types in discriminatorProperty --- src/json-inheritance.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/json-inheritance.ts b/src/json-inheritance.ts index b459422..a05258b 100644 --- a/src/json-inheritance.ts +++ b/src/json-inheritance.ts @@ -60,14 +60,23 @@ export interface DiscriminatorPropertyOptions { export function discriminatorProperty( {property, types}: DiscriminatorPropertyOptions, ): ObjectInheritanceOptions { + let resolvedTypes: {[k: string]: Serializable} | undefined; let reverseMapping: Map | undefined; + const getResolvedTypes = () => { + if (resolvedTypes === undefined) { + resolvedTypes = types(); + } + + return resolvedTypes; + }; + // Create a map for O(1) type-to-discriminator-lookup once. const getReverseMapping = () => { if (reverseMapping === undefined) { - const reverseMapItems: Array<[Function, string]> = Object.keys(types()) + const reverseMapItems: Array<[Function, string]> = Object.keys(getResolvedTypes()) .map(discriminator => { - return [types()[discriminator].prototype.constructor, discriminator]; + return [getResolvedTypes()[discriminator].prototype.constructor, discriminator]; }); reverseMapping = new Map(reverseMapItems); } @@ -81,7 +90,7 @@ export function discriminatorProperty( return result; }, resolveType: data => { - return types()[data[property]]; + return getResolvedTypes()[data[property]]; }, }; }