When declaring an array of numbers in sequelize-typescript, it triggers a TypeScript error

In my application, I am working with PostgreSQL, Sequelize, Sequelize-TypeScript, and TypeScript. I have a need for a table called Role where each role has multiple permissions of type integer. I'm following the guidelines provided in the sequelize-typescript documentation. Here is how I have defined it:

@Table
export default class Role extends Model {
    @HasMany(() => number)
    declare permissions: Number[]
}

For another model I use @HasMany(() => MyType) and MyType[], which works perfectly fine.

The issue arises when trying to implement the above code snippet as it throws the error:

'number' only refers to a type, but is being used as a value here
.

Even changing @HasMany(() => Number) to capitalize "N" results in a different error:

No overload matches this call.
Overload 1 of 2, '(associatedClassGetter: ModelClassGetter<any, unknown>, foreignKey?: string | undefined): Function', gave the following error.
    Type 'NumberConstructor' is not assignable to type 'ModelType<any, unknown>'.
    Type 'Number' is missing the following properties from type 'Model<unknown, any>': $add, $set, $get, $count, and 32 more.
Overload 2 of 2, '(associatedClassGetter: ModelClassGetter<any, unknown>, options?: HasManyOptions | undefined): Function', gave the following error.
    Type 'NumberConstructor' is not assignable to type 'ModelType<any, unknown>'.

I'm unsure of what I might be missing. Is it incorrect to use arrays of primitive types in this scenario?

PS: Changing declare permissions: Number[] to declare permissions: number[] doesn't seem to make any difference.

Answer №1

When using @HasMany, it is important to note that this only refers to relations with other models. In your case, where you need a column to store an array of numbers, it is not a relation to other models but rather a regular column.

If you wish to save an array of numbers, you can create a normal column using the @Column decorator and define it as an array of numbers specifically for PostgreSQL:

@Table
export default class Role extends Model {
    @Column(DataType.ARRAY(DataType.INTEGER)) //this defines the column type
    permissions: number[] //this is simply a TypeScript type for coding purposes
}

You can refer to the DataTypes documentation, which sequelize-typescript re-exports as DataType.

It is worth noting that when working outside of TypeScript's domain, such as in the decorator callback function, differences between JavaScript's Number object and TypeScript's number type must be considered. While they are related, they serve different purposes and have distinct use cases.

For example, you cannot return a type directly:

const bar = () => number //this will result in a compilation error as types cannot be returned as values

However, you can specify the return type of the function to be a number:

const bar = (): number => 1
const foo = (): number => Number(4)

Therefore, within the callback, only JavaScript entities should be used, explaining why classes like @HasMany(() => MyType) are functional.

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

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

Optimizing the sorting of object properties based on specific values (numbers or strings)

My goal is to simplify the process of sorting both number and string values. The first step involves checking if the parameter I've passed (which belongs to the DeliveryDetailsColumns constants) matches another parameter from a different type (Electro ...

Displaying FontIcon in a NativeScript alert box

Would it be possible to display a fonticon on a Nativescript dialog? Similar to this example? dialogs.alert({ title: // set icon as text message: "Check-in Successful" }).then(()=> { console.log("Dialog closed!"); }); Is it feasible to ...

Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students. import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm" /* * Adhering to ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

Understanding and parsing JSON with object pointers

Is it possible to deserialize a JSON in typescript that contains references to objects already existing within it? For instance, consider a scenario where there is a grandparent "Papa" connected to two parents "Dad" and "Mom", who have two children togeth ...

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Every time you try to import a config.json file in Typescript, it never fails

I have the most recent version of Visual Studio Code installed. Visual Studio Code is currently utilizing TypeScript v3.3.3. I've successfully installed the following packages via npm, both locally (save-dev) and globally: TestCafe v1.1.0 Core-JS v ...

Issue with service injection within a singleton service in Angular2

Currently, I have two services in my application. ServiceA is non-singleton and provided to components through the Providers array, while ServiceB is a singleton that is listed in its module's Providers array. Both services work perfectly fine indepen ...

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

JSX is restricted in files using the '.tsx' extension according to eslint rules (react/jsx-filename-extension)

When working in a .tsx file, why does eslint flag the following issue: The use of JSX is not permitted in files with the extension '.tsx' (eslint react/jsx-filename-extension) What steps can I take to adjust the eslint configuration and addres ...

"What is the best way to specify a type for the src attribute in a tsx file within a

<Image src= { sessionData?.user.image} alt="user" width={100} height={100} />` An issue has been encountered: There is a type error stating that 'string | null | undefined' cannot be assigned to type 'stri ...

Optimizing your data layer in Angular2: A Guide to Best Practices

As a newcomer to Angular2, I am diving into hands-on learning. My current project involves building multiple views with parent components, child components, and database services. After successfully creating one view, I am now gearing up to implement other ...

Mocha has difficulty compiling Typescript code on Windows operating system

In developing my nodejs module, I created several unit tests using Mocha and Chai. While these tests run smoothly on macOS, they encounter compilation issues on Windows, resulting in the following error: D:\projects\antlr4-graps>npm test > ...

TypeScript interface designed to capture objects containing a flexible number of values

In my possession is an object that looks like the following: { "0001": "a", "0002": "b", "0003": "c", ... } Is it possible for me to create a TypeScript interface that accurately represents this type? ...

What is the correct way to import scss files in a Next.js project?

Currently, I am working on a NextJS project that uses Sass with TypeScript. Everything is running smoothly in the development environment, but as soon as I attempt to create a build version of the project, I encounter this error. https://i.stack.imgur.com ...

Creating nested return types: A guide to defining function return types within a Typescript class

My large classes contain functions that return complex objects which I am looking to refactor. class BigClass { ... getReferenceInfo(word: string): { isInReferenceList:boolean, referenceLabels:string[] } { ... } } I am considering somethi ...

Jasmine : Techniques for monitoring a method callback using method.then()

Within my Angular 4.0.0 application, I have a method called in my component. This method is invoked within a service: this.myService.myMethod(param).then(any => { console.log("success case"); }) .catch(error => { console.log("error"); }); ...

Unable to set textAlign column property in Inovua React Data Grid using typescript

I am currently facing an issue with centering the content of each grid cell in Inovua RDG. A frustrating TypeScript error keeps popping up: Type '{ name: string; header: string; textAlign: string; defaultFlex: number; defaultVisible?: undefined; }&apo ...