How can I solve type error when cloning an object in `typescript`?

Viewed 45

I have below code. I have two types one is MyType the other is MyTypeDto. And I'd like to clone the instance of MyType to MyTypeDto but has a compile error on the assignment line: Type 'string | boolean | Date' is not assignable to type 'undefined'. Type 'string' is not assignable to type 'undefined'.

How can I solve the issue here?

interface MyType {
  str: string;
  bool: boolean;
  d: Date;
   ...
}

interface MyTypeDto {
  str?: string;
  bool?: boolean;
  d?: Date;
  name?: string;
  ...
}

const t: MyType = {
    str: "",
    bool: false,
    d: new Date(),
};

const keys = Object.keys(t);
const dto: MyTypeDto = {};

keys.forEach((key: string) => {
    dto[key as keyof MyTypeDto] = t[key as keyof MyType];  // error here
});
1 Answers

I think that best way to achieve that. Is to make custom copy function.

const copy = (myType: MyType): MyTypeDto => {
 const { str, bool } = myType;

 return {
   str,
   bool   
 }
}

You can also look at Destructin syntax with rest. Literally named after de-structuring i.e. breaking up the structure. That what you need right now.

For more than few properties. You can get interface keys using ts-transform-keys from here.

import { keys } from 'ts-transformer-keys';

interface MyType {
  str: string;
  bool: boolean;
  d: Date;
}
const keysOfMyType = keys<MyType>();

console.log(keysOfMyType); // ['str', 'bool', 'd']
Related