You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a use case where a relationship can be nullable. I defined this in the schema using the isOptional but how would I go about typing the field in the model?
Given the models in the example of this repo:
class Blog extends Model {
static table = TableName.BLOGS
static associations: Associations = {
[TableName.POSTS]: { type: 'has_many', foreignKey: 'blog_id' },
}
@field('name') name!: string;
}
class Post extends Model {
static table = TableName.POSTS
static associations: Associations = {
[TableName.BLOGS]: { type: 'belongs_to', key: 'blog_id' },
}
@field('name') name!: string;
@text("body") content!: string;
@relation(TableName.BLOGS, 'blog_id') blog!: Relation<Blog>;
}
Let's assume for the sake of example that you post a Post under no specific Blog how would: @relation(TableName.BLOGS, 'blog_id') blog!: Relation<Blog>; change?
Changing the type to Relation<Blog> | null doesnt work correctly because post.blog always return an object even the blog is nullable. And Relation<Blog | null> doesnt work because the generic that Relation takes extends Model which is not nullable.
How do I go about creating nullable relations with type safety?
The text was updated successfully, but these errors were encountered:
Hi @itsramiel , I had the same issue here and this is how I resolved it. I don't love that I'm ignoring TS errors and using a type assertion, but it does the job for me.
import{Model,RelationasWatermelonDbRelation,}from'@nozbe/watermelondb';import{Observable,}from'rxjs';/** * Wrapper of `Relation` to correctly type optional relations. These are * relations where the fk is an optional field. */exportdefaultclassOptionalRelation<TextendsModel,>extendsWatermelonDbRelation<T>{// @ts-ignorefetch(){returnsuper.fetch()asPromise<T|null>;}// @ts-ignoreobserve(){returnsuper.observe()asObservable<T|null>;}}
Hey,
I have a use case where a relationship can be nullable. I defined this in the schema using the
isOptional
but how would I go about typing the field in the model?Given the models in the example of this repo:
Let's assume for the sake of example that you post a
Post
under no specificBlog
how would:@relation(TableName.BLOGS, 'blog_id') blog!: Relation<Blog>;
change?Changing the type to
Relation<Blog> | null
doesnt work correctly becausepost.blog
always return an object even the blog is nullable. AndRelation<Blog | null>
doesnt work because the generic thatRelation
takes extendsModel
which is not nullable.How do I go about creating nullable relations with type safety?
The text was updated successfully, but these errors were encountered: