Typescript Recursive Type Aliases and the use of TypeGuards

36 views Asked by At

I am attempting to remove use of any in my code. I have this:

type jsonValue = string | number | boolean | null | Array<jsonValue> | { [key: string]: jsonValue };

const copybookResult: jsonValue = await this.getCopybookCount

copybookResult is a relatively complex object that is returned containing properties and also arrays of objects etc.

I then do this where isObject is a simple TypeGuard routine that I call to determine that I truly have an object and I also check that copybookResult.result is an array to allow me to access to its properties and perform the sort.

if (Utility.isObject(copybookResult) && 
      Array.isArray(copybookResult.result)
    ) {
      sortedCopybookResult = copybookResult.result.sort((a, b) => (a.includedComponent > b.includedComponent ? 1 : -1)); // ascending
      copybookCount = sortedCopybookResult[0].includedTotal;
    }

However Typescript is objecting to the reference within the sort of a.includedComponent and b.includedComponent with

"Property 'includedComponent' does not exist on type 'jsonValue'.
Property 'includedComponent' does not exist on type 'string'."

I can understand this but I do not see a clear solution. I could of course specify (a: any , b: any) but that defeats the objective.

I would welcome any suggestions

0

There are 0 answers