gulp-typescript compiler throws errors on readonly

2019-07-25 14:27发布

问题:

I've just upgraded my app to use Angular 2 rc.6 and Angular Material 2 alpha 8-1. These packages rely on typescript 2 and the latter makes use of the new readonly modifier.

I use gulp-typescript to compile my .ts files and I'm now getting a lot of errors from files that use the readonly modifier. For instance, this line:

readonly change: Observable<MdButtonToggleChange>;

Throws these errors during compilation:

error TS1005: '=' expected.

error TS1005: ';' expected.

error TS1005: '(' expected.

I think this is probably because gulp-typescript internally uses typescript 1.8.10, which does not have the readonly modifier.

None of my own code uses readonly; The only files throwing errors are third-party typescript definition files (.d.ts) from Angular 2 Material packages. The files in question are all within my nodes_module/ folder, and I've tried to ignore them by having the following in tsconfig.json:

"exclude": [
  "node_modules",
  "typings"
]

The errors still show up though.

  • Can I solve this?
  • If not, is there an easy way to get the compiler to ignore .d.ts files?

回答1:

One solution would be to add a TypeScript 2.0.2 RC dependency to your project (npm install typescript@rc --save-dev) and to pass it to gulp-typescript using the unofficial typescript option:

[...].pipe(ts({
    typescript: require('typescript')
}));


回答2:

@cartant got the right answer yesterday but I only saw it a minute ago. Basically, the solution is to get gulp-typescript to use the typescript 2 instead of the built-in typescript 1.8. Here is how:

1. I added typescript 2.0.2 as a devDependency in package.json

"devDependencies": {    
  "gulp-typescript": "^2.13.6",
  "typescript": "^2.0.2",
}

2. I ran npm install typescript@2.0.2

3. I edited how I created my gulp-typescript project in gulpfile.js

From:

var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json');

To:

var ts = require('gulp-typescript');
var tsProject = ts.createProject('tsconfig.json', {
    //Use TS version installed by NPM instead of gulp-typescript's built-in
    typescript: require('typescript')
});

More info. Now the compile-time errors are gone :-)