Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript intersection types and readonly properties

Tags:

typescript

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.

like image 914
Arash Avatar asked Feb 07 '26 12:02

Arash


1 Answers

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>;
like image 109
Titian Cernicova-Dragomir Avatar answered Feb 09 '26 07:02

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!