1

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.

1
  • 3
    How is AdminDefinitionType defined ? Commented Aug 11, 2022 at 18:49

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

You The Man!!! - I would love to better understand why this works though. Can you point me towards a resource I can read?
The compiler needs to ensure the value you are passing is the right one for the key. That's what the generic is doing. More on generics here : typescriptlang.org/docs/handbook/2/generics.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.