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 {
// ...