8

I have this value fetchOptions: Readonly<HttpFetchOptionsWithPath> and I'd like to overwrite one of its properties. I've tried the following:

((fetchOptions as Writable<HttpFetchOptionsWithPath>).headers as Writable<any>) = {
    'new-value': '123',
    ...(fetchOptions.headers || {}),
  };

but still get an TypeError: Cannot assign to read only property 'headers' of object '#<Request>' error.

The js code that gets executed looks like this:

fetchOptions.headers = __assign({ 'new-value': '123' }, (fetchOptions.headers || {}));

Any ideas what I'm doing wrong here?

2
  • 1
    Please if you could provide more code snippets I could help more anyway I answered based on what available in the question. hope it helps! Commented May 20, 2020 at 18:58
  • 1
    You can't, that's the point of making a property readonly. Commented May 20, 2020 at 19:04

2 Answers 2

6

You can't modify the read-only values.. what you can do is cloning these object into new instance and continue using the new instance ...

Object.assign(newVariable, JSON.parse(JSON.stringify(oldVariable)));

This also will do the job:

const newVariable={...oldVariable, propertyToModify:value}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually this answer is not incorrect but when the value of the property is a function this statement will not function well
1

With this statement you can copy and overwrite properties

var obj={...originalObj,[readOnlyProp:value]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.