Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type validated by Dictionary is different than returned type #330

Open
Hoxmot opened this issue Jun 27, 2023 · 0 comments
Open

Type validated by Dictionary is different than returned type #330

Hoxmot opened this issue Jun 27, 2023 · 0 comments

Comments

@Hoxmot
Copy link

Hoxmot commented Jun 27, 2023

Tested on:

  • @tsconfig/node18: 2.0.1
  • node: 18.15.0
  • runtypes: 6.7.0
  • typescript: 5.1.3

The type returned by validation with Dictionary differs from the type accepted by the type validator. This can lead to problems in runtime, even when we pass the type validation. I noticed it's occurring when the key in the dictionary is Union.

Here's a simple example:

const Key = Union(Literal("a"), Literal("b"));
const Dict = Dictionary(Number, Key);

const example = {
  a: 42
};
const checked = Dict.check(example);  // Runtime: OK
// Compile: OK
// Runtime: Cannot read properties of undefined (reading 'toString')
console.log(checked.b.toString(8));

It looks like the validation performed by Dictionary is different than the type it says it returns. Indeed, if we try to create this object and during the declaration, we mark it's of this type, we fail at compilation.

type Dict = Static<typeof Dict>;

// Compile: Property 'b' is missing in type '{ a: number; }' but required in type '{ a: number; b: number; }'
const typedExample: Dict = {
  a: 42
};

The object which goes through the validation should be the same as the type. It'll reduce the number of possible problems.

In my opinion, the behaviour should be that the validation checks all the required keys for existence, so in the example Dict.check(example) should fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant