GoogleFeud / ts-runtime-checks

A typescript transformer that automatically generates validation code from your types.
https://googlefeud.github.io/ts-runtime-checks/
MIT License
312 stars 7 forks source link

[BUG] Does not validate dictionary/record keys #42

Closed pipex closed 10 months ago

pipex commented 11 months ago

Describe the bug

When library types are used as dictionary keys, validation does not check that the keys have valid values

type ID = string & Matches<'/\d+/'>;

type Data = Record<ID, string>

function validate(data: Assert<Data>) {
    // Your code...
}

validate({ 123: "abc", 'xxx': 'abc' });

Playground link

https://googlefeud.github.io/ts-runtime-checks/?code=FAFwngDgpgBAkgERgXhgZxAJwJYDsDmMAZDALICGIAxgBZRoA8A5APQA6AJgNQtMB8AbmChIsBJXIoYAJShUA9pg4NEAGnRY8+PsIBmAV1xUQ2ebhgA3cgBtsHSlAAU9kOQBcMAIJo0UTCAZxVz4AShgAb2AYaJgWFhgATXl9TBgFDigAOmzgAF9hK1sXJ3CYAEYAJgBmDwAicgAjKlr1JgAPDqYPJkaqJhhckKEgA

Expected behavior

I would expect the validation function to be transpiled to something like

function validate(data) {
    if (typeof data !== "object" || data === null)
        throw new Error("Expected data to be an object");

   for (const [key, value] of Object.entries(data)) {
      if (!/\d+/.test(key)) {
         throw new Error(`Expected data key '${key}' to match '/\d+/');
      }
      // Validate value variable here
    }
}
pipex commented 11 months ago

Sorry about all the bug reports, just started playing with the library today. I'm really loving it!

GoogleFeud commented 11 months ago

This should be able to work, thanks for the bug report!