PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How to trim all string properties of a class instance?

 September 05, 2022     arrays, string, trim, typescript, typing     No comments   

Issue

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();
  }
});


Answered By - lepsch
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing