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"
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.
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.
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)
}
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With