DEV Community

Discussion on: Using a TypeScript interface to define model properties in Objection.js

Collapse
 
kwameopareasiedu profile image
Kwame Opare Asiedu

This is a hack, probably not recommended, but this can work:

class BlogPost extends Model {
    id:number;
    title: string;
    content: string;
    slug: string;
    [k: string]: any;

    static get tableName() {
        return "blog_posts";
    }
}
Enter fullscreen mode Exit fullscreen mode

Upside,

You can add your database columns as part of the model and your IDE should pick them up

Downside

Because of the [k: string]: any property, Typescript will not warn if an undefined property was accessed on instances of BlogPost.

I.e.

const post = await BlogPost.query().findById(1);
const someImportantVariable = post.undefined_property;
Enter fullscreen mode Exit fullscreen mode

The code above will fly with Typescript, instead of it previously highlighting post.undefined_property ...

Collapse
 
codefinity profile image
Manav Misra

Very nice explanation. Looking 👀 forward to hearing more in the future. Welcome!

Collapse
 
atwright147 profile image
Andy Wright

I am finding that combining this with an interface (shared with the UI) helps to keep them in sync. The interface will cause errors if your model is missing any fields

class BlogPost extends Model implements IBlog {
    ...
}
Enter fullscreen mode Exit fullscreen mode