Home > Software engineering >  Nested Object return type in Typescript
Nested Object return type in Typescript

Time:09-20

I made a function to return grand child data from object with Generic, however, Typescript throw errors because Typescript cannot infer the type. It works when the function just return child data, but it doesn't work when the function returns grand child data.

How can I make the function work?


const Name = {
  Data1: 'data1',
  Data2: 'data2'
} as const

type NameKey = typeof Name[keyof typeof Name];

type Type1Data = {
  Info1: number,
  Info2: boolean,
  Info3: string,
}

type Type1DataKey = keyof Type1Data

type Type2Data = {
  Data1: string,
  Data2: number,
  Data3: string,
  Data4: string,
}

type Type2DataKey = keyof Type2Data

type BothTypeKey = Type1DataKey | Type2DataKey

type DataType = {
  [Name.Data1]: Type1Data
  [Name.Data2]: Type2Data
}


const dataType: DataType  = {
  [Name.Data1]: {
    Info1: 1,
    Info2: true,
    Info3: 'abc'
  },
  [Name.Data2]: {
    Data1: 'abc',
    Data2: 3,
    Data3: 'abc',
    Data4: 'abcsdf'
  }
}

// Three are errors because Typescript cannot infer which data type is specified
const getGrandChild = <T extends NameKey, U extends BothTypeKey>(firstKey: T, childKey: U): DataType[T][U] => {
  return dataType[T][S]
}

// this should return boolean dataType[Name.Data1]['Info2']
const data = getGrandChild(Name.Data1, 'Info2') 

TS Playground

CodePudding user response:

You can use below function with three generic parameters representing each level of depth of your objects hierarchy:

const getGrandChild = 
  <TObj, 
   TChildKey extends keyof TObj, 
   TGrandChildKey extends keyof TObj[TChildKey]>
   (data: TObj, key1: TChildKey, key2: TGrandChildKey)  => {
       return data[key1][key2];
   }

const data = getGrandChild(dataType, Name.Data1, 'Info2') // boolean

TS Playground

Alternatively you can use DataType type directly, try:

TS Playground (2)

  • Related