如果有人可以帮助解决以下打字稿错误,我将不胜感激。
感谢。
我正在使用以下code,其中包含以下内容。它需要能够链接Promise
。
line 26: dbPromise = _db.execute(sql)
当我尝试构建它时,我得到以下内容:
ERROR in ./app/pages/chats/SqlDatabase.ts (26,9): error TS2322: Type 'Promise<SqlResultSet>' is not assignable to type 'Promise<SqlDatabase>'. Type 'SqlResultSet' is not assignable to type 'SqlDatabase'. Property '_db' is missing in type 'SqlResultSet'.
我正在使用Typescript version 2.0.3.
代码:
import { isBrowser } from './platform';
import { SqlResultSet } from './SqlResultSet';
export class SqlDatabase {
constructor(private _db: any) { }
static open(name: string, initStatements: string[] = []): Promise<SqlDatabase> {
let dbPromise = isBrowser()
.then(browser => {
const openDatabase = browser ? openBrowserDatabase : openCordovaDatabase;
return openDatabase(name);
});
if (initStatements.length === 0) {
return dbPromise;
}
let _db: SqlDatabase;
// execute the first statement and capture the _db
dbPromise.then(db => {
_db = db;
return db.execute(initStatements.shift());
});
// execute all the other statements (if any) sequentially
for (let sql of initStatements) {
dbPromise.then(() => {
dbPromise = _db.execute(sql)
});
}
// resolve the _db only after all statements have completed
return new Promise((resolve, reject) => {
console.log('resolve: ', resolve);
dbPromise.then(() => resolve(_db)).catch(reject);
});
}
execute(statement: string, params: any[] = []): Promise<SqlResultSet> {
console.log('execute: ' + statement);
return new Promise((resolve, reject) => {
this._db.transaction(tx => tx.executeSql(statement, params, (tx, resultSet) => {
console.log('execute: resolve: ', resultSet);
resolve(resultSet);
}, (tx, error) => {
reject(error)
}));
});
}
}
declare var sqlitePlugin: any;
function openCordovaDatabase(name: string): Promise<SqlDatabase> {
return new Promise((resolve, reject) => {
if (typeof sqlitePlugin === 'undefined') {
reject(new Error('[ionix-sqlite] sqlitePlugin global object not found; did you install a Cordova SQLite plugin?'));
}
const db = sqlitePlugin.openDatabase({
name: name,
location: 'default'
});
console.info('[ionix-sqlite] using Cordova sqlitePlugin');
resolve(new SqlDatabase(db));
});
}
declare function openDatabase(name: string, version: string, desc: string, size: number): any;
function openBrowserDatabase(name: string): Promise<SqlDatabase> {
return new Promise((resolve, reject) => {
try {
const db = openDatabase(name, '1.0', name, -1);
console.info('[ionix-sqlite] using WebSQL');
resolve(new SqlDatabase(db));
} catch (error) {
reject(error);
}
});
}
答案 0 :(得分:1)
错误是由于您尝试更改dbPromise
的类型
首次宣布时:
let dbPromise = isBrowser()
.then(browser => {
const openDatabase = browser ? openBrowserDatabase : openCordovaDatabase;
return openDatabase(name);
});
编译器将类型引用到Promise<SqlDatabase>
(基于错误),但之后您尝试分配其他内容:
dbPromise = _db.execute(sql)
类型Promise<SqlResultSet>
。
您可以这样解决:
let dbPromise: Promise<any> = ...
或者你可以有两个不同的承诺变量(即:dbPromise: Promise<SqlDatabase>
和resultPromise: Promise<SqlResultSet>
),这对我来说听起来更好。