Home > Software engineering >  Parameter type as value of key in generic interface
Parameter type as value of key in generic interface

Time:08-10

I've tried my hardest to make a type-safe, generic function that sets values into an object constrained to a specified interface. To make it a bit more clear of what I'm trying to achieve, here's what I've already come up with:

export interface OrderFormData {
  start?: {
    startDate?: string;
  };
  verification?: {
    validFrom: Date;
    validTo: Date;
  };
}

export class FormDataService {
  testFormData: any = {};
  
  public testSetFormData<T>(key: keyof T, value: T[keyof T]) {
    this.testFormData = this.testFormData as T;
    this.testFormData[key] = value;
  }

  func() {
    this.testSetFormData<OrderFormData>('start', '')
  }
}

Now, this isn't too bad! But instead of showing me what type I can pass for the value-Parameter, it gives me a list of the different types for all keys in the interface:Error showing all different key-types

Instead of showing me all kinds of entries, I'd like to reduce it down to the type of the value of the key in my interface (in above case it'd only show me Argument of type '""' is not assignable to parameter of type '{ startDate?: string; }').

I've already tried testSetFormData<T>(key: keyof T, value: T[key]) {...}, that doesn't seem to be valid syntax though. Any ideas on how to incorporate the first parameter into the type of the second parameter?

TS Playground

CodePudding user response:

If you want to target specifics properties, it would be more appropriate to use setters function for each property and not to use generics.

But if you want to target any property and use generics, then you could try something like this :

function setFormData<T>(object: Partial<T>) {
  testFormData = {...testFormData, ...object }
}

setFormData<OrderFormData>({ start: "" })
  • Related