2016-03-16 3 views
0

Я только что закончил Угловой 2,0 тур героев учебника, и я добавил следующий глоток файл (упрощенный для данного примера), чтобы построить его:Машинопись выбрасывает ошибку с Array.find

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

gulp.task('transpile-ts', function() { 
    var tsResult = gulp.src(paths.allTypeScript) 
     .pipe(sourcemaps.init()) 
     .pipe(ts(tsProject)); 

    return tsResult.js 
     .pipe(sourcemaps.write('.')) 
     .pipe(gulp.dest(paths.dest_js)); 
}); 

Я хочу добавить метод Array.find в dashboard.component.ts следующим образом:

ngOnInit() { 
    let newVar: Array<number> = new Array(); 
    newVar.push(0); 
    newVar.push(1); 
    newVar.find(d => d == 1); 

    this._heroService.getHeroes() 
     .then(heroes => this.heroes = heroes.slice(1,5)); 
} 

Когда я запускаю команду «глоток transpile-ц», однако я получаю следующее сообщение об ошибке:

app \ dashboard.component.ts (26,16): ошибка TS2339: свойство 'find' не существует по типу 'number []'.

У меня есть es6-shim.d.ts, поэтому метод «find» существует под «интерфейсом Array».

Также я попытался выполнить ту же задачу с Grunt и возникла одна и та же проблема, так что это не проблема Gulp.

Любые идеи относительно того, что может быть причиной этого?

ответ

1

После расследования я заметил, что при использовании 'tsc' в линии CMD для пересылки Typsecript все работало, как ожидалось. Вместо использования «gulp.src» в моем файле gulp я должен был использовать «tsProject.src» для эмуляции этого.

Это результат ответа https://github.com/ivogabe/gulp-typescript/issues/313.

+0

Спасибо, только то, что мне нужно! – evandongen

5

I have es6-shim.d.ts included so the "find" method does exist under "interface Array".

Видимо, что прокладка не добавляет метод find к массиву. Вы должны иметь:

interface Array<T> { 
    /** 
     * Returns the value of the first element in the array where predicate is true, and undefined 
     * otherwise. 
     * @param predicate find calls predicate once for each element of the array, in ascending 
     * order, until it finds one where predicate returns true. If such an element is found, find 
     * immediately returns that element value. Otherwise, find returns undefined. 
     * @param thisArg If provided, it will be used as the this value for each invocation of 
     * predicate. If it is not provided, undefined is used instead. 
     */ 
    find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T; 
} 

Update

Даже несколько объявлений не должно привести к ошибке. Следующие компилирует просто отлично:

interface Array<T> { 
    /** 
     * Returns the value of the first element in the array where predicate is true, and undefined 
     * otherwise. 
     * @param predicate find calls predicate once for each element of the array, in ascending 
     * order, until it finds one where predicate returns true. If such an element is found, find 
     * immediately returns that element value. Otherwise, find returns undefined. 
     * @param thisArg If provided, it will be used as the this value for each invocation of 
     * predicate. If it is not provided, undefined is used instead. 
     */ 
    find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T;  

} 
interface Array<T> { 
    /** 
     * Returns the value of the first element in the array where predicate is true, and undefined 
     * otherwise. 
     * @param predicate find calls predicate once for each element of the array, in ascending 
     * order, until it finds one where predicate returns true. If such an element is found, find 
     * immediately returns that element value. Otherwise, find returns undefined. 
     * @param thisArg If provided, it will be used as the this value for each invocation of 
     * predicate. If it is not provided, undefined is used instead. 
     */ 
    find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T;  
} 

var foo:any[] 
foo.find((x)=>true); 

Так проверьте содержимое ES6-shim.d.ts, чтобы убедиться, что это подтверждает.

+0

Спасибо за ваш ответ basarat. У меня есть этот код в файле es6-shim, и я даже могу перейти к нему. У меня есть несколько вариантов, когда я «выбираю декларацию» в свойстве «найти» с такими файлами, как «global.d.ts», не уверен, что это имеет к этому какое-то отношение. –

+0

Неправильные декарации не должны вызывать ошибки. См. Обновление. – basarat

+0

Я нашел проблему с "gulp-typescript". Когда я использую только tsc, эта ошибка исчезает. Использование только tsc также разрешает эту ошибку http://stackoverflow.com/questions/36001159/using-public-variables-and-interfaces-in-external-libraries-when-using-typescrip/36002069#36002069. Есть ли у вас опыт работы с «gulp-typescript»? Спасибо –

Смежные вопросы