打字机:angular.d.ts用ng.IPromise打字

时间:2015-12-06 18:30:52

标签: javascript angularjs typescript typescript1.5

我在尝试连接ng.IPromise函数调用时遇到此错误:

Error:(101, 23) TS2345: Argument of type 'IPromise<IResult[]>' is not assignable to parameter of type 'IResult[]'. Property 'length' is missing in type 'IPromise<IResult[]>'.

代码:

&#13;
&#13;
public search(stateParams : any, page : any) : ng.IPromise<Array<app.search.entities.IResult>> {

	// create promise
	let deferred : ng.IDeferred<Array<app.search.entities.IResult>> = this.$q.defer();

	// ensure page is a number
	page = (isNaN(page))	?	1	:	parseInt(page, 10);

	// create query
	this.searchServiceSearchQuery.getQuery(
		stateParams,
		this._itemsPerPage,
		(page * this._itemsPerPage) - this._itemsPerPage,
		null
	).then(
		(query : any) : void => {

			// search
			deferred.resolve(this._search(query)); // <= THIS "this" THROWS THE ERROR ABOVE

		}
	);

	// return promise
	return deferred.promise;

}


private _search(query : any) : ng.IPromise<Array<app.search.entities.IResult>> {

// create deferred
let deferred : ng.IDeferred<Array<app.search.entities.IResult>> = this.$q.defer();

// run query
this.coreServiceRestangularHelpmeSearch
	.one('search')
	.get({q : query})
	.then(
		(data : any) : void => {

			// found results
			if (
				data !== null &&
				'results' in data === true
			) {

				// create entities
				let entities : Array<app.search.entities.IResult> = [];

				// walk through all results
				data.results.forEach((result : any) : void => {

					// create entity
					let entity : app.search.entities.IResult = new app.search.entities.Result(
						result.id,
						result.cat1Ids[0],
						result.cat2Ids[0],
						result.cat3Ids[0],
						result.typeCode,
						(result.sort) 			?	parseInt(result.sort, 10)	:	null,
						result.title,
						result.description,
						this.$sce.trustAsHtml(result.summary),
						false
					);

					entities.push(entity);

				});

				// sort all by sort key
				entities.sort(
					(
						a : app.search.entities.IResult,
						b : app.search.entities.IResult
					) : number => {

						if (a.getSortKey() > b.getSortKey()) {

							return 1;

						} else if (a.getSortKey() < b.getSortKey()) {

							return -1;

						}

						return 1;

					}

				);

				deferred.resolve(this._extendResults(entities));

			}

			// return empty object
			deferred.reject('invalid api response');

		},
		() : any =>  {

			deferred.reject('failed to fetch search results');

		}

	)

;
&#13;
&#13;
&#13;

我做错了什么或def版本文件有问题吗?如果我将_search()函数的泛型更改为any,则一切正常。

1 个答案:

答案 0 :(得分:0)

在内部解析方法中,您应该传递类型的变量:

Array<app.search.entities.IResult>

不是类型:

ng.IPromise<Array<app.search.entities.IResult>>.

如果您写这样的代码,您的代码将是正确的:

this._search(query).then((data)=>{
     deferred.resolve(data);
});

而不是

deferred.resolve(this._search(query));

它将被编译,但我不知道你的代码逻辑,自己调整它。