Search code examples
arraystypescriptstringtrimtyping

How to trim all string properties of a class instance?


I have an instance of some class. Let's say this class is Person:

class Person {
    name?: string | null;
    age?: number | null;
    friends!: Person[];
    isLucky: boolean;
}

How to iterate over this instance and call trim() method on all properties that are strings? Because if I'm trying to do this:

(Object.keys(person) as (keyof typeof person)[]).forEach((key) => {
  const value = person[key];
  if (typeof value === 'string') {
    person[key] = value.trim();
  }
});

My friend Typescript shows this error:

Type 'string' is not assignable to type 'person[keyof person]'.

I want to write an all around method suitable for instances of different classes with many different properties. Is there a way to achieve this in Typescript? May be some typing magic?


Solution

  • I would do it this way. Just cast it to any.

    (Object.keys(person) as (keyof typeof person)[]).forEach((key) => {
      const value = person[key];
      if (typeof value === 'string') {
        (person as any)[key] = value.trim();
      }
    });