2

So I am Having this small little function for pinia. Where I do throw in an ID of my Object to filter it (result is of type Task | undefined) I am giving in a Key which should of course be a keyof Task and now I kind of struggle with the value part. I've tried to find out what serves my usecase best, it must be something like a value Of or so but I do currently not find the correct Utility Type (if it even should be one).

changeValue(id: number, key: keyof Task , value: Partial<Task>) {
    const task = this.one(id);
    
    if (task) {
        task[key] = value;
    }
}

Also I have a Second Problem here that task[key] says its of type never can anyone explain why this is of type never?

Mirko t.
  • 481
  • 2
  • 11

1 Answers1

0

You could make your code work simply by leveraging the TypeScript inference with proper control flow:

changeValue(id: number, key: keyof Task , value: Partial<Task>) {
    const task = this.one(id);
    
    if(task === undefined)
        return; // Handle the undefined case
    
    const propToAssign = value[key];

    if(propToAssign === undefined)
        return; // Handle the undefined case

    task[key] = propToAssign;
}
Guerric P
  • 30,447
  • 6
  • 48
  • 86