Home > OS >  How to append data to a TS object?
How to append data to a TS object?

Time:01-03

Basically I have an API that returns an object, and I want to add a field to it. Simple, but I can't figure out how to make TS happy. It either wants my extra field when I'm creating the object, or it wants it to be optional (which it isn't, it just doesn't exist for one line of code):

function createThing() {
    return {x: 42};
}

const myThing: ReturnType<typeof createThing> & {y: number} = createThing(); // complains that y doesn't exist
myThing.y = 43;

ts playground

CodePudding user response:

Not sure if I understood your requirement, but I think you are looking for Object.assign

function createThing() {
    return {x: 42};
}

const myThing = Object.assign(createThing(), {y: 3});
console.log(myThing.x); // 42
console.log(myThing.y); // 3

Playground Example

CodePudding user response:

Do you know the value of y while the assignment of myThing? If so, you might want to use one of these solutions:

  • const myThing: ReturnType<typeof createThing> & { y: number } = { ...createThing(), y: 43 };
  • Let TypeScript infer the type with const myThing = { ...createThing(), y: 43 };
  • Related