'Typescript mutate object add property
I have the following code:
type Data = {
projectID: number;
foo: string;
}
const projectID = 1;
const datas: Data[] = []
const addToProject = (a: Omit<Data, "projectID">) => {
a.projectID = projectID; // Property 'projectID' does not exist on type 'Omit<Data, "projectID">'
datas.push(a);
};
addToProject({
foo: 'bar',
});
The idea is that the object passed to addToProject doesnt need a projectID property, since in the given context, the projectID is already known and can be added by the function itself.
Inside the function, a is converted from Omit<Data, "projectID"> to Data.
How can I tell Typescript that I am changing the type of a?
I could change the function body to:
datas.push({
...a,
projectID
});
but for performance reasons I don't want to create a new object.
I could also change every a to a as Data
(a as Data).projectID = projectID;
datas.push(a as Data);
but my real function has a lot more occurrences of a and this doesn't seem right.
Solution 1:[1]
There you are
const addToProject = (a: Omit<Data, "projectID">) => {
const r = a as Data;
r.projectID = projectID; // Property 'projectID' does not exist on type 'Omit<Data, "projectID">'
datas.push(r);
};
But, honestly, I'd just create a new object. The performance impact is minuscule and it outweighs the risk of mutating an argument.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Igor Loskutov |
