0

I want to implement deep clone object with typescript.But exist an error I can't deal with it not.

export function cloneDeep <T>(obj: T): T  {
  if (!obj || typeof obj !== 'object') {
    return obj
  }

  const result: any = isArray(obj) ? [] : {}
  return Object.keys(obj).forEach((key: keyof T) => {
    if (obj[key] && typeof obj[key] === 'object') {
      result[key] = cloneDeep(obj[key])
    } else {
      result[key] = obj[key]
    }
  })
}

Error message

TS2345: Argument of type '(key: keyof T) => void' is not assignable to parameter of type '(value: string, index: number, array: string[]) => void'. Types of parameters 'key' and 'value' are incompatible. Type 'string' is not assignable to type 'keyof T'.

1 Answer 1

0

Two problems:

  1. Object.keys always returns the keys as strings (hence the incompatibility with keyof T).
  2. Array.prototype.forEach does not return anything.
export function cloneDeep<T>(obj: T): T  {
  if (!obj || typeof obj !== 'object') {
    return obj
  }

  const result: any = isArray(obj) ? [] : {};

  // Drop annotation of `key`.
  Object.keys(obj).forEach(key => {
    if (obj[key] && typeof obj[key] === 'object') {
      result[key] = cloneDeep(obj[key])
    } else {
      result[key] = obj[key]
    }
  });

  // Return result
  return result;
}
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.