Skip to content

Commit

Permalink
op 1
Browse files Browse the repository at this point in the history
  • Loading branch information
stopachka committed Dec 31, 2024
1 parent 4819517 commit eeacdf1
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 15 deletions.
44 changes: 29 additions & 15 deletions client/packages/core/src/schemaTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,6 @@ export class DataAttrDef<ValueType, IsRequired extends boolean> {
// }
}

type ExtractValueType<T> =
T extends DataAttrDef<infer ValueType, infer isRequired>
? isRequired extends true
? ValueType
: ValueType | undefined
: never;

export class LinkAttrDef<
Cardinality extends CardinalityKind,
EntityName extends string,
Expand Down Expand Up @@ -90,9 +83,7 @@ export class EntityDef<
) {}

asType<
_AsType extends Partial<{
[AttrName in keyof Attrs]: ExtractValueType<Attrs[AttrName]>;
}>,
_AsType extends Partial<MappedAttrs<Attrs>>,
>() {
return new EntityDef<Attrs, Links, _AsType>(this.attrs, this.links);
}
Expand Down Expand Up @@ -231,13 +222,36 @@ type LinksIndexedByEntity<
};
};

type RequiredKeys<Attrs extends AttrsDefs> = {
[K in keyof Attrs]: Attrs[K] extends DataAttrDef<any, infer R>
? R extends true
? K
: never
: never;
}[keyof Attrs];

type OptionalKeys<Attrs extends AttrsDefs> = {
[K in keyof Attrs]: Attrs[K] extends DataAttrDef<any, infer R>
? R extends false
? K
: never
: never;
}[keyof Attrs];

/**
* MappedAttrs:
* - Required keys => `key: ValueType`
* - Optional keys => `key?: ValueType`
*/
type MappedAttrs<Attrs extends AttrsDefs> = {
[K in RequiredKeys<Attrs>]: Attrs[K] extends DataAttrDef<infer V, any> ? V : never;
} & {
[K in OptionalKeys<Attrs>]?: Attrs[K] extends DataAttrDef<infer V, any> ? V : never;
};

export type ResolveEntityAttrs<
EDef extends EntityDef<any, any, any>,
ResolvedAttrs = {
[AttrName in keyof EDef["attrs"]]: ExtractValueType<
EDef["attrs"][AttrName]
>;
},
ResolvedAttrs = MappedAttrs<EDef["attrs"]>
> =
EDef extends EntityDef<any, any, infer AsType>
? AsType extends void
Expand Down
1 change: 1 addition & 0 deletions client/sandbox/strong-init-vite/instant.schema.v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const _schema = i.schema({
entities: {
messages: i.entity({
content: i.string(),
createdAt: i.date().optional(),
}),
$users: i.entity({
email: i.string().unique().indexed(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,14 @@ const messagesQuery = {
} satisfies InstaQLParams<AppSchema>;

type CoreMessage = InstaQLEntity<AppSchema, "messages">;
const mWithOptionalFieldWorks: CoreMessage = {
id: '1',
content: 'hello',
};

// to silence ts warnings
mWithOptionalFieldWorks;

let coreMessage: CoreMessage = 1 as any;
coreMessage.content;

Expand Down

0 comments on commit eeacdf1

Please sign in to comment.