Skip to content

Comment on Adding type safety to object IDs in TypeScript

Comments

If you want a type-prefixed UUIDv7 type, I can wholeheartedly recommend TypeID-JS: https://github.com/jetpack-io/typeid-js

Also available for a whole bunch of other languages: https://github.com/jetpack-io/typeid

UUIDv7 is UUIDv4-compatible (i.e. you can put a v7 UUID anywhere a v4 UUID would go, like in Postgres's UUID datatype) and is time-series sortable, so you don't lose that nice lil' benefit of auto-incrementing IDs.

And if you use something like TypeORM to define your entities, you can use a Transformer to save as plain UUIDv7 in the DB (so you can use UUID datatypes, not strings), but deal with them as type-prefixed strings everywhere else:

    export const TYPEID_USER = 'user';

    export type UserTypeID = TypeID<'user'>;
    
    export type UserTypeString = `user_${string}`;
    
    export class UserIdTransformer implements ValueTransformer {
      from(uuid: string): UserTypeID {
        return TypeID.fromUUID(TYPEID_USER, uuid);
      }
    
      to(tid: UserTypeID): string {
        assert.equal(
          tid.getType(),
          TYPEID_USER,
          `Invalid user ID: '${tid.toString()}'.`,
        );
    
        return tid.toUUID();
      }
    }
    
    @Entity()
    export class User {
      @PrimaryColumn({
        type: 'uuid',
        primaryKeyConstraintName: 'user_pkey',
        transformer: new UserIdTransformer(),
      })
      id: UserTypeID;
    
      @BeforeInsert()
      createNewPrimaryKey() {
        this.id = typeid(TYPEID_USER);
      }
    }
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.