Home > Software engineering >  TypeScript Will Not Let Me Set Value of Object in Array
TypeScript Will Not Let Me Set Value of Object in Array

Time:08-12

Why will TypeScript not let me set the value of an object inside an array that I have the exact location of?

list: AdminDefinitionType[];
activeIndex: number;

async updateDefinition(id: keyof AdminDefinitionType, value: string | number | boolean) {
  if (value === this.list[this.activeIndex][id]) {
    return true; // No Change
  } else {
    this.list[this.activeIndex][id] = value;  // 'string | number | boolean' is not assignable to type 'never' - WTF???
    const definition: AdminDefinitionType = await clerk.update(this.list[this.activeIndex])
  }
},

I feel like I have tried everything. I thought it might be because it may be thinking active index could be out of bounds, but I wrapped it in an if to ensure it was and still no luck.

How can I fix this error?


Update

export type AdminDefinitionType = {
  id?: number;
  name: string;
  sort: number;
  disabled: boolean;
};

This is my admin definition type. There are quite a few more props that don't need to be posted here, but they are all typed as strings and not optional.

CodePudding user response:

You need to specify the type for the key. You can do this with a generic

  async updateDefinition<K extends keyof AdminDefinitionType>(id: K, value: AdminDefinitionType[K]) {
    if (value === this.list[this.activeIndex][id]) {
      return true; // No Change
    } else {
      this.list[this.activeIndex][id] = value; // OK
      const definition: AdminDefinitionType = await clerk.update(this.list[this.activeIndex])
    }
  }

Playground

  • Related