如何使用dexie解析打字稿日期类型?

时间:2019-08-06 15:42:29

标签: json typescript date dexie

我有一个Dexie数据库,其中包含一个基于接口的表,我希望能够使用this.tableName.bulkAdd(rations);(定量引用一个json文件)插入批量测试数据。但是我找不到在json文件中公式化日期的方法,以使Dexie理解可以将其解析为Typescript Date类型。

要插入数据库的代码如下(仅精简到与问题相关的部分):

import rations from '../utils/data/Ration.json';

export class Database extends Dexie {
    rations: Dexie.Table<IRation, string>;

    constructor() {
        super('Database');
        this.version(1).stores({
            rations: '$$rationId'
        });
        this.rations = this.table(DatabaseTableNames.rations);

        this.addMockDataIfNeeded();
    }

    private addMockDataIfNeeded() {
        this.rations.count().then(
            (data) => {
                if (data <= 0) {
                    this.fillDatabaseWithMockData();
                }
            }
        );
    }

    private fillDatabaseWithMockData() {
        this.rations.bulkAdd(rations);
    }
}

界面如下:

export interface IRation {
  rationId: string;
  rationName: string;
  rationDate: Date;
  status: string;
  rationArticles: AnotherClass[];
}

和json文件如下:

[
    {
        "rationId": "asdfasdadvfdws",
        "rationName": "ration 1",
        "rationDate": "2019-08-06T12:04:06.123Z",
        "status": "yay",
        "rationArticles": [
            {},
            {},
            {}
        ]
    },
    {
        "rationId": "asvsdbfhgdfdws",
        "rationName": "ration 2",
        "rationDate": "2019-08-06T12:04:06.123Z",
        "status": "yay",
        "rationArticles": [
            {},
            {},
            {}
        ]
    },
    {
        "rationId": "adsafdfbgtsvfs",
        "rationName": "ration 3",
        "rationDate": "2019-08-06T12:04:06.123Z",
        "status": "yay",
        "rationArticles": [
            {},
            {},
            {},
            {},
            {}
        ]
    }
]

我收到以下错误:

ERROR in src/app/services/database.service.ts(66,30): error TS2345: Argument of type '{ "rationId": string; "rationName": string; "rationDate": string; "status": string; "rationArticles": { ...AnotherBigObject... }; "sortId": number; "weight...' is not assignable to parameter of type 'IRation[]'.
[ng]   Type '{ "rationId": string; "rationName": string; "rationDate": string; "status": string; "rationArticles": { ...AnotherBigObject... }; "sortId": number; "weight...' is not assignable to type 'IRation'.
[ng]     Types of property 'rationDate' are incompatible.
[ng]       Type 'string' is not assignable to type 'Date'.

通过使用this.rations.bulkAdd(rations as unknown as IRation[]);,我发现了一种解决方法,它可以正常工作,但是那样一来,您将放弃所有类型检查,并且再也无法避免其他意外错误。有没有更好的解决方案,我如何可以在不丢失类型检查的情况下插入此json数据?我可以用dexie / typescript会理解的正确类型的另一种方式来表示Date json数据吗?该字符串已经可以在Date的构造函数中使用,以创建有效的Date对象。

0 个答案:

没有答案