Issue
I am using PostgreSQL, Sequelize, Sequelize-TypeScript and TypeScript for my application. I need a Role
table in which each role
has multiple permissions
(of type integer). I am following the sequelize-typescript docs. My declaration is as follows:
@Table
export default class Role extends Model {
@HasMany(() => number)
declare permissions: Number[]
}
For a similar model I use @HasMany(() => MyType)
and MyType[]
. That works as expected.
However this piece of code throws the following error: 'number' only refers to a type, but is being used as a value here
.
When using @HasMany(() => Number)
(capital "N") I get another 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>'.
What am I missing? Am I not supposed to use arrays of primitive types?
PS: changing declare permissions: Number[]
to declare permissions: number[]
does not seem to have any impact.
Solution
@HasMany refers only to relations to other models, and by your description you need a column to hold an array of numbers, which is not a relation to other models, it is just a regular column.
If you want to save an array of numbers, create a normal column with the @Column decorator and since it's postgres, define it as an array of numbers:
@Table
export default class Role extends Model {
@Column(DataType.ARRAY(DataType.INTEGER)) //this is the actual column type
permissions: number[] //this is just a typescript type, for usage in the code
}
Here are the docs for DataTypes, which sequelize-typescript re-exports as DataType
Something that you are strugling also, is using types outside of typescript domain, like in the callback of the decorator, Number is a primitive object that exists in javascript while number is a basic type that exists in typescript only, and so, it can only be used in types. The two have a correlation, but are different things.
You cannot return a type:
const bar = () => number //it will throw a compilation error, as you cannot use a type as a value
But you can define it as the return type of the function
const bar = (): number => 1
const foo = (): number => Number(4)
So inside the callback, you can only use something that exists in javascript, that is why other classes like @HasMany(() => MyType)
work.
Answered By - Alykam Burdzaki
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.