Repository navigation
Closed
Labels
typescriptFor issues and PRs. Things that involve typescript, such as typings and intellisense.
Description
Issue Description
What are you doing?
// this is a copy of https://sequelize.org/master/manual/typescript.html
import { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';
import { HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';
class User extends Model {
public id!: number; // Note that the `null assertion` `!` is required in strict mode.
public name!: string;
public preferredName!: string | null; // for nullable fields
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
// Since TS cannot determine model association at compile time
// we have to declare them here purely virtually
// these will not exist until `Model.init` was called.
public getProjects!: HasManyGetAssociationsMixin<Project>; // Note the null assertions!
public addProject!: HasManyAddAssociationMixin<Project, number>;
public hasProject!: HasManyHasAssociationMixin<Project, number>;
public countProjects!: HasManyCountAssociationsMixin;
public createProject!: HasManyCreateAssociationMixin<Project>;
// You can also pre-declare possible inclusions, these will only be populated if you
// actively include a relation.
public readonly projects?: Project[]; // Note this is optional since it's only populated when explicitly requested in code
public static associations: {
projects: Association<User, Project>;
};
}
const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');
class Project extends Model {
public id!: number;
public ownerId!: number;
public name!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
class Address extends Model {
public userId!: number;
public address!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Project.init({
id: {
type: DataTypes.INTEGER.UNSIGNED, // you can omit the `new` but this is discouraged
autoIncrement: true,
primaryKey: true,
},
ownerId: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
}
}, {
sequelize,
tableName: 'projects',
});
User.init({
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
},
preferredName: {
type: new DataTypes.STRING(128),
allowNull: true
}
}, {
tableName: 'users',
sequelize: sequelize, // this bit is important
});
Address.init({
userId: {
type: DataTypes.INTEGER.UNSIGNED,
},
address: {
type: new DataTypes.STRING(128),
allowNull: false,
}
}, {
tableName: 'address',
sequelize: sequelize, // this bit is important
});
// Here we associate which actually populates out pre-declared `association` static and other methods.
User.hasMany(Project, {
sourceKey: 'id',
foreignKey: 'ownerId',
as: 'projects' // this determines the name in `associations`!
});
Address.belongsTo(User, {targetKey: 'id'});
User.hasOne(Address,{sourceKey: 'id'});
async function stuff() {
// Please note that when using async/await you lose the `bluebird` promise context
// and you fall back to native
const newUser = await User.create({
name: 'Johnny',
preferredName: 'John',
});
console.log(newUser.id, newUser.name, newUser.preferredName);
const project = await newUser.createProject({
name: 'first!',
});
const ourUser = await User.findByPk(1, {
include: [User.associations.projects],
rejectOnEmpty: true, // Specifying true here removes `null` from the return type!
});
console.log(ourUser.projects![0].name); // Note the `!` null assertion since TS can't know if we included
// the model or not
}My tsconfig:
"compilerOptions": {
"outDir": "dist",
"sourceMap": false,
"allowJs": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"resolveJsonModule": true,
"module": "commonjs",
"strictNullChecks": true,
"allowSyntheticDefaultImports": true,
"lib": ["es7", "es2015", "dom"],
"target": "es2015",
"baseUrl": "."
}What do you expect to happen?
I expect ourUser.projects to be defined
What is actually happening?
console.log(ourUser.projects) // undefinedContext
Note that I also observe some strange behavior: when I add the flag raw: true in the query, the result looks like this:
{
id: 1,
createdAt: 2019-11-06T08:35:49.172Z,
updatedAt: 2019-11-06T08:35:49.172Z,
'projects.id': 1,
'projects.ownerId': 1,
'projects.createdAt': 2019-11-08T12:41:40.520Z,
'projects.updatedAt': 2019-11-08T15:32:42.822Z
}Environment
- Sequelize version: 5.21.2
- Node.js version: v10.16.3
- Operating System: OSX
- TypeScript version: 3.6.3
Issue Template Checklist
How does this problem relate to dialects?
- I think this problem happens regardless of the dialect.
- I think this problem happens only for the following dialect(s):
- I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX
Would you be willing to resolve this issue by submitting a Pull Request?
- Yes, I have the time and I know how to start.
- Yes, I have the time but I don't know how to start, I would need guidance.
- No, I don't have the time, although I believe I could do it if I had the time...
- No, I don't have the time and I wouldn't even know how to start.
Reacted by Eduardo Daniel Cuomo, Giovanni Patruno and Tom Moor
Reacted by Eduardo Daniel Cuomo
Reacted by Tom Moor
Metadata
Metadata
Assignees
Labels
typescriptFor issues and PRs. Things that involve typescript, such as typings and intellisense.
Activity
nicgirault commentedon Nov 14, 2019
For French readers: this post helped me understand what is happening: https://openclassrooms.com/forum/sujet/proprietes-de-classe-avec-node-12-babel. It seems there is a conflict with babel class properties. Migrating to node v12 and removing babel plugin
@babel/proposal-class-propertiessolved my issuereduardo7 commentedon Sep 22, 2021
What about it? How can I make it work?
reduardo7 commentedon Sep 22, 2021
StackOverflow thread: https://stackoverflow.com/questions/66515762/configuring-babel-typescript-for-sequelize-orm-causes-undefined-properties
reduardo7 commentedon Sep 22, 2021
From https://sequelize.org/master/manual/typescript.html, the TypeScript definition for model initialization is correct, but the documentation is not correct!
When you use the null assertion (
public id!: number; // Note that the "null assertion" "!" is required in strict mode), this make the attribute asundefinedat instance initialization.My idea is to force the model initialization using
getDataValue()at Model Constructor and avoid to use the recommended null assertion.Example
Source: https://stackoverflow.com/a/69289067/717267
jaismith commentedon Oct 30, 2021
also having this issue, does anyone know of a workaround or patch ETA? currently using
.getDataValueto retrieve all my field values, which is somewhat messy...ephys commentedon Nov 3, 2021
@jaismith
If you're using babel: This is an issue with babel setting the fields to
undefined. Your options are to:declareon your fields: https://babeljs.io/docs/en/babel-preset-typescript#allowdeclarefields (you need to enable the option in the typescript preset config)jaismith commentedon Nov 4, 2021
@ephys Not using babel, just
ts-nodeplustsconfig-paths.node16typescript4.4.3tsconfig.targetisesnextedit: I was able to get this working by setting my target to
es6, is there a flag to set to get that working on a newer target?ephys commentedon Dec 30, 2021
@jaismith Have you tried using
declareon your fields? (even with tsc/ts-node).ephys commentedon Jan 2, 2022
Merged #13877
Sparrowan commentedon Mar 20, 2024
This worked for me