Is there a way to receive autocomplete suggestions for sequelize classes that extend the Model class?

I have a specific Post class that I've created with various properties defined within it. However, I often find myself struggling to remember all the fields when actually typing them out, leading to errors in my code.

@Table
class Post extends Model {
    @Column
    declare imgUrl: string

    @Column
    declare userId: string

    @Column
    declare username: string
    
    @Column
    declare profileImgUrl: string
}

When instantiating a new Post object, such as in the example below, I sometimes forget to include all the necessary fields but do not receive any errors from vscode:

const post = new Post({
    imgUrl: 'http://localhost/image.png',
    profileImgUrl: 'http://localhost/image.png',
    username: 'johnsmith',
})

My main question is how can I configure vscode to display all the class fields when hovering over it, and also provide error messages when I forget to include certain fields so that I don't have to constantly refer back to the source code for reference?

Answer №1

To modify your code successfully, simply update class Post extends Model to

class Post extends Model<Post>
.

Refer to the Model class declaration in the source code on https://github.com/sequelize/sequelize/blob/main/packages/core/src/model.d.ts:

export abstract class Model<TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes>
  extends ModelTypeScript {
  //...
  /**
   * Builds a new model instance.
   *
   * @param values an object of key value pairs
   * @param options instance construction options
   */
  constructor(values?: MakeNullishOptional<TCreationAttributes>, options?: BuildOptions);
  // ...
}

This means passing the Post class as the argument for generics parameter TModelAttributes.

The behavior you desire can be achieved with the extracted parts from sequelize.js library:

// Code snippets from sequelize.js

// Type definitions
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type NullishPropertiesOf<T> = {...};
type MakeNullishOptional<T extends object> = ...;

// Model classes
class Model<TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes> {
   constructor(values?: MakeNullishOptional<TCreationAttributes>) {}
}

class Post extends Model<Post> {
   declare imgUrl: string;
   declare userId: string;
}

new Post({
  // fill in the fields
});

If all fields are not filled, an error like this will arise:

Error: Argument of type '{}' is not assignable to parameter of type 'MakeNullishOptional<Post>'.
  Type '{}' is missing properties: imgUrl, userId

For other types used in this example, visit https://github.com/sequelize/sequelize/blob/main/packages/core/src/utils/types.ts.

Also, consider using InferAttributes and InferCreationAttributes such as

extends Model<InferAttributes<Foo>, InferCreationAttributes<Foo>>
.


Regarding your query about displaying all fields when hovering over the class:

How can I show all fields when hovering over the class?

Add a documentation comment to your Post class like so:

/**
 * Documentation comment here...
 */
@Table
class Post extends Model {
  // ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

Mastering the TypeScript syntax for executing the MongoDB find method

Having trouble properly typing the find method of MongoDB in my TypeScript project that involves MongoDB. Here's the snippet I'm working on: import { ReitsType } from '@/app/api/types/reits'; import { NextRequest, NextResponse } from &a ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

Error message: "The property is not found within the specified type when using the OR operator with

Within my Angular component, I am faced with a challenge involving an Input that can be one of two types. @Input() profile: UserProfileDetails | BusinessProfileDetails; The structure of the profile template is straightforward and I want to avoid duplicati ...

How to simulate keyboard events when a dropdown list is opened in an Angular application

Requirement- A situation arises where upon opening the dropdown menu, pressing the delete key on the keyboard should reset the index to -1. Steps to reproduce the issue: 1. Click on the dropdown and select an option from the menu. 2. Click on the dropdow ...

Typescript: organizing nested types within an interface

My goal is to create an interface CountersData based on my JSON data. The challenge lies in the nested id property, which contains an array of nested dictionaries. I want this property to be optional. However, I have not been successful in making it option ...

Angular Pause until the variable is ready

I am in the process of developing a new web application service. The first step involves obtaining a token through the rest API. Once this token is obtained, it needs to be sent as a header to retrieve additional information. The issue I'm facing is ...

Activate the Sass IntelliSense feature specifically for .vue files within the VS Code editor

Could IntelliSense for Sass be activated in .vue documents without connecting them to sass, as this may disrupt other extensions dependent on the .vue file association? ...

Can you explain the distinction between Reflect.getMetadata and Reflect.getOwnMetadata?

Just like the title says, the reflect-metadata API comes with a method called getMetadata and another called getOwnMetadata. Can you explain the distinction between them? The same question applies to hasOwnMetadata, and so on. ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

Traveling from one child route to another

I am encountering issues with route navigation between child routes, as I keep receiving "routes not found" errors. Despite trying multiple solutions like injecting and refreshing after child configuration, I still face difficulties in navigating to a spec ...

What is the process for displaying the attributes of a custom object in Typescript?

I need help returning an array of prop: value pairs for a custom object using the myObject[stringProp] syntax. However, I keep encountering this error message: TS7053: Element implicitly has an 'any' type because expression of type 'str ...

Creating a TypeScript interface that has keys determined by the elements in an array

My goal is to create a function that returns a record with keys specified by a string array. For example: // return type -> { itemA:SomeType,itemB:SomeType } const res = doThing(['itemA', 'itemB']) Do you think this is achievable? ...

Replace a portion of text with a RxJS countdown timer

I am currently working on integrating a countdown timer using rxjs in my angular 12 project. Here is what I have in my typescript file: let timeLeft$ = interval(1000).pipe( map(x => this.calcTimeDiff(orderCutOffTime)), shareReplay(1) ); The calcTim ...

Can anyone provide a solution for fixing TypeScript/React error code TS7053?

I encountered an error message with code TS7053 which states: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'. No index signa ...

How can I display table rows along with their child table rows in Angular?

Is there a way to display API data in a table using Angular? The table should have collapsible rows with nested child rows. This is the JSON file structure: { "collapse1": [ { "name": "Soil", "budget": 12345, "child": [ { ...

Retrieve a specific number from an equation

With my limited knowledge of TypeScript, I am attempting to extract a specific number from an expression. The goal is to locate and retrieve the digit from the following expression. ID:jv.link.weight:234231 In the given string, I aim to extract the numb ...

Resetting the initial values in Formik while utilizing Yup validation alongside it

Currently, I am working on a React application with Typescript and using Formik along with Yup validation. However, I have encountered an issue with setting values in a Select element. It seems that the value is not changing at all, or it may be resettin ...

`Creating a union of prop types in TypeScript and React`

I'm facing an issue with a component prop that I need to restrict to specific strings using a union type, as shown below: type HeadingProps = { level?: 'h1' | 'h2' | 'h3' | 'h4'| 'h5' | 'h6&a ...