Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript how to clone object except for one key

Tags:

typescript

I have two interfaces. They are really similar except for one key.

interface InitialStateFromDB {
  uploads: {
    companyImage: string,
    map: string
  },
  adminPasswords: string,
  postInfos: PostInfo[] | undefined
}

interface InitialState extends Omit<InitialStateFromDB, 'adminPasswords'> {
  adminPasswords: AdminPassword
}

And I get initialState from DB.

const initialStateFromDB: InitialStateFromDB = window.__PRELOADED_STATE__;

Then I extract value of each property from initialStateFromDB to make initialState.

let adminPasswords: AdminPassword = JSON.parse(initialStateFromDB.adminPasswords);
const initialState : InitialState = {
  uploads : initialStateFromDB.uploads,
  adminPasswords,
  postInfos: initialStateFromDB.postInfos
}

But I think there is a more simple way to merge except adminPasswords property. So I searched about this.

Clone a js object except for one key

But, I don't know how to do like that in typescript.

So, My question is that "How to clone object except for one key in Typescript"

like image 251
Byeongin Yoon Avatar asked Apr 26 '19 02:04

Byeongin Yoon


People also ask

How do I clone a TypeScript object?

Use the Object. assign() Method to Clone an Object in TypeScript. The Object. assign() works similarly as in the case of the spread operator and can be used to clone simple objects, but it fails in the case of nested objects.

How can we copy object without mutating?

Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.


2 Answers

What you need is spread operator (check the "Object Spread and Rest" part). Typescript is a superset of JavaScript, both of them support this feature.

const {adminPasswords, ...state} = initialStateFromDB;
const initialState: InitialState = {
  ...state,
  adminPasswords: JSON.parse(adminPasswords)
}
like image 134
Xie Guanglei Avatar answered Oct 16 '22 23:10

Xie Guanglei


I found one option that works if you want to omit the key entirely instead of overriding it - using ts object rest (ref documentation here):

In the case of the question asked, it'd be:

const {adminPasswords, ...initialState} : InitialState = {...initialStateFromDB};

The line above makes a copy of 'initialStateFromDB' excluding the 'adminPasswords' field. The new object created is 'initialState'.

like image 22
Halima Olapade Avatar answered Oct 16 '22 23:10

Halima Olapade