React Native 如何获取expo-sqlite的类型?

1l5u6lss  于 2023-03-19  发布在  React
关注(0)|答案(5)|浏览(96)

在expo sdk版本33中,sqlite被移到了它自己的包expo-sqlite中,现在我无法加载类型。
代替

import {SQLite} from 'expo';

我有

import {SQLite} from 'expo-sqlite';

但是类型没有被加载。
我得到以下类型错误:

Cannot find namespace 'SQLite'.
p1tboqfb

p1tboqfb1#

您似乎尚未下载该模块。请安装并应用该模块。

npm install expo-sqlite
blmhpbnm

blmhpbnm2#

expo-sqlite包中缺少类型。我在Expo的GitHub页面上打开了一个问题,问题已经解决。
GitHub问题:https://github.com/expo/expo/issues/5264
Github拉取请求:https://github.com/expo/expo/pull/5544

5tmbdcev

5tmbdcev3#

我遇到了同样的问题,并创建了一个类型声明文件来解决这个问题。
https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html
我从这个包https://www.npmjs.com/package/@types/expo中复制了声明
这是声明https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/expo/v31/index.d.ts#L2467
我的项目现在在src文件夹中有一个expo-sqlite.d.ts文件,如下所示

declare module 'expo-sqlite' {
  export namespace SQLite {
    type Error = any;

    interface Database {
      transaction(
        callback: (transaction: Transaction) => any,
        error?: (error: Error) => any, // TODO def of error
        success?: () => any
      ): void;
    }

    interface Transaction {
      executeSql(
        sqlStatement: string,
        arguments?: string[] | number[],
        success?: (transaction: Transaction, resultSet: ResultSet) => any,
        error?: (transaction: Transaction, error: Error) => any
      ): void;
    }

    interface ResultSet {
      insertId: number;
      rowAffected: number;
      rows: {
        length: number;
        item: (index: number) => any;
        _array: HashMap[];
      };
    }

    function openDatabase(
      name:
        | string
        | {
            name: string;
            version?: string;
            description?: string;
            size?: number;
            callback?: () => any;
          },
      version?: string,
      description?: string,
      size?: number,
      callback?: () => any
    ): any;
  }
}
r6l8ljro

r6l8ljro4#

如果您的问题是访问SQLResultSetRowList中的数据,那么我建议您定义一个类似CustomResultset的接口来扩展SQLResultSetRowList。
例如:

import * as SQLite from 'expo-sqlite';

interface CustomResultSet extends SQLite.SQLResultSetRowList {
    _array: [],
}

这可能不是最佳解决方案,但您应该能够通过_array属性访问Data,而不会在代码中出现类型错误。

a64a0gku

a64a0gku5#

运行以下命令进行安装:

npx expo install expo-sqlite

并导入到项目中:

import * as SQLite from 'expo-sqlite';

const db = SQLite.openDatabase('DBName.db');

设置数据库:

const setupDatabaseAsync = async () => {
  return new Promise((resolve, reject) => {
    db.transaction((tx) => {
      tx.executeSql(
        'CREATE TABLE IF NOT EXISTS table_name (id INTEGER PRIMARY KEY NOT NULL, name TEXT);',
        [],
        (tx, success) => {
          resolve(success);
          console.log('SUCCESS IN SETUP DB');
        },
        (err) => {
          reject(err);
          console.log('ERROR IN SETUP DB');
        }
      );
    });
  });
}

或者,如果不想编写查询,可以使用expo-sqlite-orm

相关问题