0

I would like to know if it is possible to type the following function without using any.

Playground

type MyType = {
  name: string,
  age: number,
  score: {
    prime: number,
  },
  prize: {
    first: {
      discount: number
    }
  }
}

export const trim = (
    myObj: MyType
): MyType => {
    const trimRecursive = (obj: any) => {
        for (let key in obj) {
            if (obj[key] && typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
                trimRecursive(obj[key]);
            } else {
                if (typeof obj[key] === 'string') {
                    obj[key] = obj[key].trim();
                }
            }
        }
        return obj;
    };

    return trimRecursive(myObj);
};

2
  • Where are you using any? Commented Feb 3, 2022 at 14:36
  • sorry, I made an edit to my question, (obj :any) Commented Feb 3, 2022 at 16:39

1 Answer 1

0

It might be a footgun, as this comment points out, but here's how I did it. I used forEach to be able to assign a type.


export const trim = <T>(myObj: T):T => {
  const trimRecursive = <T>(obj: T): T => {
    (Object.keys(obj) as Array<keyof T>).forEach((key) => {
      if (
        obj && typeof obj[key] === "object" && !Array.isArray(obj[key])
      ) {
        trimRecursive(obj[key])
      } else {
        if (typeof obj[key] === 'string') {
          obj[key] = (obj[key] as unknown as string).trim() as unknown as T[keyof T]
        }
    }
  })
    return obj
  }
  return trimRecursive(myObj)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.