I have an object, and I need to add some extra properties to it in some cases.
interface Item {
name: string
}
functi
obj = obj as WithFoo
does not work because the type of obj
is Item
and you want to store in it an object of type WithFoo
.
But you can use another variable of type WithFoo
and store obj
in it. Because obj
is an object, both variables will keep references to the same data:
interface Item {
name: string
}
function addProp(obj: Item) {
type WithFoo = Item & { foo?: string; }
const foo = obj as WithFoo;
if (obj.name == 'test') {
foo.foo = 'hello';
}
}
const x1: Item = { name: 'test' }
addProp(x1);
console.log(x1);
const x2: Item = { name: 'not-matching' }
addProp(x2);
console.log(x2);
Try it online.