jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.31k stars 356 forks source link

TypeScript: special case for auto-incrementing primary keys #151

Closed dumbmatter closed 3 years ago

dumbmatter commented 4 years ago

This adds an optional string autoIncrementKeyPath property to the DBSchemaValue type. When present, any values returned from idb (such as from get or getAll) will have a numeric value at that key value.

I tried it in a project I'm porting from my own untyped IndexedDB promise wrapper to idb with the goal of reducing the number of anys in my code, and it's really cool to see this working!

On the other hand, I understand that this is a little complicated and possibly more confusing than it's worth, so I'd appreciate your thoughts!

It also might be worth adding some tests of the TypeScript types like described here to ensure that it continues to work in the future. I'm not sure though, I've never done something like that.

Resolves #150

jakearchibald commented 4 years ago

In terms of type tests, do you mean something different to what's already there, eg https://github.com/jakearchibald/idb/blob/master/test/main.ts#L39?

This PR is cool, but the final solution should work for deeply nested keys too, so I don't think specifying a path is the right way forward — as you said in the other thread, Typescript can't walk the path based on a string.

jakearchibald commented 4 years ago

I wonder if we could provide a key type like AutoIncrementingKey:

interface MyDB extends DBSchema {
  posts: {
    value: {
      title: string;
      body: string;
      id: AutoIncrementingKey;
    };
    key: number;
  };
}

Then, internally, we could do something like:

type MyDBWithOptionalKeys = MakeAutoIncrementingKeyOptional<MyDB>;

I don't know how possible that would be with a deeply nested key, but it kinda feels possible.

dumbmatter commented 4 years ago

In terms of type tests, do you mean something different to what's already there, eg https://github.com/jakearchibald/idb/blob/master/test/main.ts#L39?

...I did not see that! Any eventual solution to this issue should include some tests there :)

I don't know how possible that would be with a deeply nested key, but it kinda feels possible.

That's an interesting idea, I will have to think about it, which probably will consist of a post on Stack Overflow.

dumbmatter commented 4 years ago

After thinking about it a little, I couldn't figure it out, so here is the Stack Overflow question I predicted would happen.

If it's not possible and you still want to support nested keys, another solution would be to optionally have two value properties on DBSchemaValue, one with the primary key and one without. That's slightly less fancy, but fancy is not necessarily good, even if it is possible!