I want to update an object of type IMessage
with a new object with the same type
interface IMessage {
id: string,
text: string,
// and many more attributes
}
const message: IMessage = {
id: "_id",
text: "old text",
// and many more attributes
}
const newMessage: IMessage = {
id: "_id",
text: "new text"
// and many more attributes
}
I am expecting my message
after updating will have value exactly the same with newMessage
, but I cannot just reassign message
object because message
is declared as a const
. This is what I have so far
const updateMessage = (message: any, newMessage: typeof message): void => {
for (const attr in newMessage) {
if (attr !== "id" && newMessage.hasOwnProperty(attr)) {
message[attr] = newMessage[attr];
}
}
};
This function is working. But in this function, I have to declare (message: any, newMessage: typeof message)
, otherwise Typescript will throw a warning Element implicitly has an 'any' type because type 'IMessage' has no index signature
. How can I make this function accept only arguments with type IMessage
?