I'm trying to write a piece of code in TypeScript that boils down to this pattern:
function test(x: {theFlag: boolean} & {readonly theFlag: boolean} ){
x.theFlag = true;
}
But I get the following error on this line x.theFlag = true;
[ts] Cannot assign to 'theFlag' because it is a constant or a read-only property.
I don't know why TypeScript is giving me an error on this. I think logically this should be allowed.
Is there a good workaround to achieve what I'm trying to do?
I'm using TypeScript version 2.7.2.
I think the compiler is playing it safe, since the property is readonly in one of the constituent types, it is readonly in the intersection.
In 2.8 you can easily create a type that removed the readonly from any property:
type Mutable<T> = { -readonly [P in keyof T]: T[P]};
function test(x: Mutable<{theFlag: boolean} & {readonly theFlag: boolean}> ){
x.theFlag = true;
}
In 2.7 and below, I think the following definition of Mutable should do the trick, I don't use any 2.8 syntax, but I don't have an old version to test:
type MutableHelper<T, TNames extends string> = { [P in TNames]: (T & { [name: string]: never })[P]};
type Mutable<T> = MutableHelper<T, keyof T>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With