【问题标题】:Realm Object relationships using typescript使用打字稿的领域对象关系
【发布时间】:2020-03-04 15:14:28
【问题描述】:

我正在实现一个领域模型。 (与此处讨论的类似:https://github.com/realm/realm-js/issues/1795)。

class Artist {
    // [index: string]: any;
    public static schema: Realm.ObjectSchema = {
            name: 'Artist',
            primaryKey: 'identifier',
            properties: {
                name:  'string',
                identifier: 'string',
                albums: 'Album[]',
            }
    };

    public name: string;
    public identifier: string;

    constructor(name: string, identifier: string) {
        this.name = name;
        this.identifier = identifier;
    }

    public hasAlbum(album: Album): boolean {
        const filteredAlbums: Realm.Results<Album> = this.albums.filtered("identifier == $0", album.identifier);
        return filteredAlbums.length > 0;
    }
};

这在打字稿中效果很好,因为我只需要声明变量及其类型。 问题从声明对象关系开始,例如:

properties: {
    albums: 'Album[]'
}

在领域架构中。这告诉 Realm 我们想要一个专辑列表(这也是一个模型)。 现在我需要告诉 typescript 我的班级有一个名为 Albums 的属性。

  1. 选项:作为数组
public albums: Album[];

这样做的缺点是我不能使用 Realm.Results 的方法,例如过滤或其他方法。此外,我还需要使用一个值来初始化数组,该值在技术上会覆盖从数据库返回的内容。

  1. 选项:作为 Realm.Results
public albums: Realm.Results<Album>;

这里的问题是我必须直接或在构造函数中给它一个值。我不能给它一个真正的值(也不存在一个空的结果构造)。

  1. 选项:添加索引签名(删除属性声明)

我可以添加: [index: string]: any;到我的班级,让我做各种操作。 这样做会引发一个问题,如果它没有警告我类型安全,为什么我应该使用 typescript,因为我关闭了它。

有人知道如何在 typescript 中声明属性“而不初始化”它们并在我的类中使用它们吗?

谢谢!

【问题讨论】:

    标签: typescript realm


    【解决方案1】:

    在几分钟前搜索了这个确切的问题后,我想我想通了。

    对于您的特定用途,您可以这样输入

    public albums: Realm.List<Album & Realm.Object>;
    

    现在我得到了预期的智能感知类型提示。 Realm.Object 似乎是必要的,因为如果您只返回一个元素。它只有 Album 类型,我们不能将它作为 Realm.Object 使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      相关资源
      最近更新 更多