POV
POV

Reputation: 12005

How to improve function TypeScript using generic types?

There are some similar parts in my code:

  for (let j = 0; j < this.homeworkList.length; j++) {
    this.homeworkList[
      j
    ].subjectName = LocalService.getDictionaryEntryStatic(
      this.homeworkList[j].subjectId
    );
  }

Or this:

  for (let j = 0; j < this.data.length; j++) {
    this.data[
      j
    ].name = LocalService.getDictionaryEntryStatic(
      this.data[j].id
    );
  }

As you can see both codes change array and set new property by value from LocalService.getDictionaryEntryStatic().

I can apply generic type for this function.

  function mapObject<T>(data: T, key: string, newPropertyName:string) {
        for(let i = 0; i < data.length; i++) {
               data[i][newPropertyName] = LocalService.getDictionaryEntryStatic(data[i][key]);
        }
    }

Do you have any recommendations how to improve this function?

Upvotes: 1

Views: 38

Answers (2)

Paleo
Paleo

Reputation: 23682

You can ensure that the key is an actual property of your data items:

function mapObject<T extends object, U extends keyof T>(
    list: T[], key: U, newPropertyName: string
) {
    for (const item of list) {
        item[newPropertyName] = LocalService.getDictionaryEntryStatic(item[key]);
    }
}

… Or just not use generics at all:

function mapObject(list: object[], key: string, newPropertyName:string) {
    for (const item of list) {
        item[newPropertyName] = LocalService.getDictionaryEntryStatic(item[key]);
    }
}

Upvotes: 1

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

There is actually not that much point of using generics here. You can simply use

function mapObject(data: Array<any>, key: string, newPropertyName: string)

Or if you want to use generics, then something like this

function mapObject<T extends Array<U>, U extends { [index: string]: any }>(data: T, key: string, newPropertyName: string)

Upvotes: 1

Related Questions