cypher-builder icon indicating copy to clipboard operation
cypher-builder copied to clipboard

Add generic parameter to `NodePatternOptions` to improve type safety for `properties`

Open CharlieDigital opened this issue 5 months ago • 4 comments

Currently, when using methods that accept NodePatternOptions such as Cypher.Pattern() and .to(), there is no enforcement of types in the key of properties.

By adding a type parameter on these methods and on NodePatternOptions, it is then possible to enforce type safety by using the keyof the type as the key of the Record

export type NodePatternOptions<T> = {
    labels?: string | string[] | LabelExpr;
    properties?: Record<keyof T, Expr>;
};

Example in TS Playground

Image

Similarly, it would be nice to be able to specify a type on the .related() like:

export const VALID_RELATIONS = [
  'HAS'
] as const

export type ValidRelations = (typeof VALID_RELATIONS)[number]

new Cypher.Pattern(...)
   .related<ValidRelations>({ type: 'HAS'}) ✅

new Cypher.Pattern(...)
   .related<ValidRelations>({ type: 'NO_LONGER_HAS'}) ❌

This ensures that when creating nodes, all properties are provided.

CharlieDigital avatar Jul 29 '25 20:07 CharlieDigital

Hi @CharlieDigital

This is a neat idea, it could also be applied to other places such as variable.property()

angrykoala avatar Jul 30 '25 08:07 angrykoala

I would super appreciate more type safety in this library. I recognize that neo4j is loosely typed, but in practice you almost always need some sort of structure to rely on and and it would be great to support that common case. kysely is a good example of a query builder doing some clever things to give you strong and flexible typing

aleffert avatar Aug 13 '25 18:08 aleffert

Hi @aleffert thanks for the reference, that's very helpful

I'm all for adding options to improve type safety, although that can be tricky in such a low level query builder as this.

I guess most of the missing type safety comes from the data model (i.e. movies have title etc...) as the original post mentions. Are there other missing/incorrect types in the query builder itself that are causing issues?

Any code example of the preferred interface to add types would be helpful.

angrykoala avatar Aug 14 '25 09:08 angrykoala

I'm just starting out using it and am new to neo4j in general, so don't have many useful thoughts yet. But I appreciate your interest in better typing support. I didn't take a close look at it (because it's no longer maintained), but https://github.com/jamesfer/cypher-query-builder seemed to have some interesting ideas around that. But happy to help workshop inasmuch as I can add anything useful

aleffert avatar Aug 14 '25 15:08 aleffert