简体   繁体   English

如何修剪 class 实例的所有字符串属性?

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

I have an instance of some class.我有一些 class 的实例。 Let's say this class is Person:假设这个 class 是 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?如何迭代此实例并在所有字符串属性上调用 trim() 方法? 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:我的朋友 Typescript 显示此错误:

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?有没有办法在 Typescript 中实现这一点? May be some typing magic?可能是一些打字魔术?

I would do it this way.我会这样做。 Just cast it to any .只需将其投射到any .

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

TypeScript isn't able to determine if the key is associated with a specific typed key from Person, only that it's one of them. TypeScript 无法确定密钥是否与来自 Person 的特定类型的密钥相关联,只能确定它是其中之一。 So you'll get a type of never when accessing person[key] without any other specific checks on key .因此,在没有对key进行任何其他特定检查的情况下访问person[key]时,您将获得一种never

The quickest answer is to narrow your key:最快的答案是缩小密钥范围:

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

Alternatively you could do the .trim() in your class constructor and avoid this entirely, but it's unclear what the context is for your issue.或者,您可以在 class 构造函数中执行.trim()并完全避免这种情况,但尚不清楚您的问题的上下文是什么。

Generally I avoid doing a forEach to map an Object and might favor Object.from over an Object.entries with a .map() or reconsider the data structure entirely depending on what your actual use case might be. Generally I avoid doing a forEach to map an Object and might favor Object.from over an Object.entries with a .map() or reconsider the data structure entirely depending on what your actual use case might be.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM