2

I have a node.js project where I successfully use a custom mapped type

export type Mutable<T> = {
    -readonly [P in keyof T]: T[P];
};

but if I add the same code to an Angular 6 project, compilation fails saying:

ERROR in src/assets/scripts/utils.ts(2,5): error TS1131: Property or signature expected.
src/assets/scripts/utils.ts(2,27): error TS1005: ']' expected.
src/assets/scripts/utils.ts(2,28): error TS1005: ';' expected.
src/assets/scripts/utils.ts(14,29): error TS1128: Declaration or statement expected.
src/assets/scripts/utils.ts(3,1): error TS1128: Declaration or statement expected.

Why does this happen and how can I solve?

Thank you all in advance!!

Sergio
  • 2,078
  • 3
  • 24
  • 41

2 Answers2

2

You are using an older version of typescript (2.7 or below). The ability to remove the readonly modifier explicitly was only added in 2.8 (see PR and Roadmap).

You can use a trick to achieve the remove readonly result in prior versions of typescript as described here

type MutableHelper<T, TNames extends string> = { [P in TNames]: (T & { [name: string]: never })[P]};
type Mutable<T> = MutableHelper<T, keyof T>;
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • keyof T is marked as error, saying: Type 'keyof T' does not satisfy the constraint 'string'. Type 'string | number | symbol' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. – Sergio Jul 31 '18 at 12:54
  • @Sergio Hm .. I think your visual studio is using 3.0, while your build uses 2.7... you can switch the version VS uses from the lower right corner.. In 2.9 I think `keyof T` is not only a `string` but also `string | number | symbol` – Titian Cernicova-Dragomir Jul 31 '18 at 12:58
  • I'm using current vscode's version, which is 2.9.2. – Sergio Jul 31 '18 at 13:03
  • @Sergio, you need to tell VS code to use 2.7 since that is the version you are compiling with, otherwise you will get inconsistent errors between build and vscode. This might be useful: https://stackoverflow.com/questions/39668731/what-typescript-version-is-visual-studio-code-using-how-to-update-it – Titian Cernicova-Dragomir Jul 31 '18 at 13:05
  • 1
    tried to downgrade from 2.9.2 to 2.7.2 (ng 6) but got too many errors, I think I'll use 2 separate versions, and avoid sharing that bit of code. It's just a school project ... Thank you for your time sir! – Sergio Jul 31 '18 at 13:20
  • casually found out that, in order to use your code with 2.9+, you can do `Extract` (if you want to update your reply! :D) – Sergio Jul 31 '18 at 13:59
  • 1
    @Sergio yeah, I am aware of `Extract` but that is a 2.8+ feature, and the work around is supposed to be 2.7 or lower... – Titian Cernicova-Dragomir Jul 31 '18 at 14:00
  • ahem, didn't even check hahah forget it then – Sergio Jul 31 '18 at 14:03
2

The latest @angular/cli@6.1.1 uses typescript@~2.7.2 and mapped type is a feature of @typescript@^2.8.

lenilsondc
  • 9,590
  • 2
  • 25
  • 40