我試圖在作爲Cesium屬性的公共3-D建模框架(描述爲here)中包含when.js(github上的公共Promise庫,可以找到here)一個Typescript定義文件,用於Cesium庫。這是因爲我試圖將一些使用Cesium的項目的JavaScript文件轉換爲Typescript,並且引用的Cesium.js代碼包含下面的代碼片段。但是,我對如何在d.ts文件中聲明when.js感到不知所措。它似乎不是一個類,我不認爲它是一個接口。我應該如何去處理這個屬性 - 它是一個什麼樣的對象?在Typescript定義文件中定義未知類型的Javascript函數
(function(define) { 'use strict';
define('ThirdParty/when',[],function() {
var reduceArray, slice, undef;
//
// Public API
//
when.defer = defer; // Create a deferred
/* more when.otherProperties set here */
/**
* Register an observer for a promise or immediate value.
*
* @param {*} promiseOrValue
* @param {function?} [onFulfilled]
* @param {function?} [onRejected]
* @param {function?} [onProgress]
* @returns {Promise}
*/
function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
// Get a trusted promise for the input promiseOrValue, and then
// register promise handlers
return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
}
/**
* @param {*} promiseOrValue the rejected value of the returned {@link Promise}
* @returns {Promise} rejected {@link Promise}
*/
function reject(promiseOrValue) {
return when(promiseOrValue, rejected);
}
/* more functions defined here, including a 'defer' function */
示例代碼引用此:
static getData(/* vars */) {
/* stuff */
return Cesium.when.reject('message here');
}
目前我可以得到上述代碼工作,如果我聲明一個類被稱爲「何時」在Cesium.d.ts文件我有。唯一的問題是,在這種情況下,「when」是一個構造函數,但正如代碼片段中明確定義的那樣,函數「when」返回一個Promise。
我試過了工作(因爲它編譯和運行的感覺可能打破一些打字稿愛好者的心):
declare module Cesium {
/* a lot of other functions, classes, interfaces, enums... */
class when extends Promise<any> {
constructor(promiseOrValue: any, onFulfilled?: Function, onRejected?: Function, onProgress?: Function);
static reject(promiseOrValue: any): Promise<any>;
}
}
任何意見是極大的讚賞。
編輯
在繞過多一點戳上打字稿文檔之後,我越來越確信,我需要的是一個hybrid type。但是,由於它被聲明爲接口,TS編譯器不會將其識別爲Cesium的屬性。
這裏是我的嘗試:
interface when {
(promiseOrValue: any, onFulfilled?: Function, onRejected?: Function, onProgress?: Function): any
reject(promiseOrvalue: any): any;
}
這導致在編譯時出現以下錯誤:
TS2339: Property 'when' does not exist on type 'typeof Cesium'.
什麼是準確導出? – lilezek
銫庫。它包含此第三方「when.js」。最初我在網上下載了一個Cesium.d.ts文件(https://gist.github.com/mgiraldo/f07432df1ccc50a0ea6e),但它沒有在這個定義文件中定義。 – anon