0
votes

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

1 Answers

0
votes

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