网站搜索

typescript - 类型 typeof * 上不存在属性 * - 静态父方法


React Native、TypeScript 代码 JS(非 TS)ORM 模块:

父类 BaseModel:

export default class BaseModel {
  static createTable() {
    ...
  }
  ...

我的 Animal 模型没有重新定义该方法,它只是被定义为:
export default class Animal extends BaseModel { ...

现在这段代码 await Animal.createTable(); 实际上可以运行,但是 VSCode 的 TypeScript 检查器在代码中会给出以下错误:

Property 'createTable' does not exist on type 'typeof Animal'.ts(2339)

这是编辑器/检查器的问题吗?还是说 JS/TS 代码应该以某种更好的方式定义?

答案#1

所以这似乎是 vscode typescript 智能感知在分析纯 JS 模块(不是 typescript)时出现的问题。因为如果我在项目中用 typescript 创建中间层基础模型,它就能识别得很好。你必须重新定义并代理所有使用的方法到包的父级,但这仍然比将它们添加到每个模型中要轻松得多。

可选地,任何 ts 错误都可以通过在该行之前放置 // @ts-ignore 来忽略,但如果可以避免,我 不建议 这样做,因为这可能会隐藏重要错误。

// @ts-ignore
someLineWithTSerror;

我的解决方案:

AppBaseModel.tsx
import * as SQLite from 'expo-sqlite'
import { BaseModel } from 'expo-sqlite-orm'

export default class AppBaseModel extends BaseModel {
    constructor(obj) {
        super(obj)
    }

    static get database(): any {
        return async () => SQLite.openDatabase('MyAppDemoDB.db')
    }

    static createTable(): Promise<any> {
        return super.createTable();
    }

    static query(options): Promise<any> {
        return super.query(options);
    }

    save(): Promise<any> {
        return super.save();
    }
    // ...

}
Animal.tsx
import { types } from 'expo-sqlite-orm'

import AppBaseModel from 'pathToAppBaseModel/AppBaseModel'

export default class Animal extends AppBaseModel {
    constructor(obj) {
        super(obj)
    }

    static get tableName() {
        return 'animals'
    }

    static get columnMapping() {
        return {
            id: { type: types.INTEGER, primary_key: true }, // For while only supports id as primary key
            name: { type: types.TEXT, not_null: true },
            color: { type: types.TEXT },
            age: { type: types.NUMERIC },
            another_uid: { type: types.INTEGER, unique: true },
            timestamp: { type: types.INTEGER, default: () => Date.now() }
        }
    }
}

示例测试使用

import { useEffect } from 'react';
import { Alert } from 'react-native';
import Animal from 'pathToAnimal/Animal'

// ... const SomeComponent = ({navigation}) => { ...

useEffect(() => {

    const testDB = async () => {
        await Animal.createTable();

        const props = {
            name: 'Bob',
            color: 'Brown',
            age: 2
        };

        const animal: Animal = new Animal(props);
        const save_result = await animal.save();
        let X_TEST = await Animal.query({
            columns: 'id, name',
            page: 1,
            limit: 30,
        });
        //X_TEST = [animal, save_result];
        Alert.alert ("X", JSON.stringify(X_TEST, null, 2));
    };
    testDB().catch(console.error);

});