Skip to content

Commit

Permalink
fix(types): support union in CreationAttributes (sequelize#14146)
Browse files Browse the repository at this point in the history
  • Loading branch information
ephys authored and aliatsis committed Jun 2, 2022
1 parent cedd2eb commit d86137f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/utils.d.ts
Expand Up @@ -163,4 +163,6 @@ export type UndefinedPropertiesOf<T> = {
* name: string,
* };
*/
export type MakeUndefinedOptional<T extends object> = Optional<T, UndefinedPropertiesOf<T>>;
// 'T extends any' is done to support https://github.com/sequelize/sequelize/issues/14129
// source: https://stackoverflow.com/questions/51691235/typescript-map-union-type-to-another-union-type
export type MakeUndefinedOptional<T extends object> = T extends any ? Optional<T, UndefinedPropertiesOf<T>> : never;
29 changes: 29 additions & 0 deletions test/types/create.ts
@@ -1,5 +1,7 @@
import { expectTypeOf } from 'expect-type'
import { User } from './models/User';
import { Model } from 'sequelize';
import { UserGroup } from './models/UserGroup.js';

(async () => {
const user = await User.create({
Expand Down Expand Up @@ -72,3 +74,30 @@ import { User } from './models/User';
unknown: '<unknown>',
});
})();

// reasons for this test: https://github.com/sequelize/sequelize/issues/14129
(async () => {
interface User2Attributes {
groupId: number;
}

type User2CreationAttributes = { id: number } & (
| { groupId: number }
| { group: { id: number } }
);

class User2 extends Model<User2Attributes, User2CreationAttributes> {
declare groupId: number;
declare group?: UserGroup;
}

await User2.create({
id: 1,
groupId: 1,
});

await User2.create({
id: 2,
group: { id: 1 },
}, { include: [User2.associations.group] });
})();

0 comments on commit d86137f

Please sign in to comment.