woutervh- / typescript-is

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Doesn’t Seem to Detect Additional Keys

FlorianWendelborn opened this issue · comments

Either I’m doing something wrong, or this is not yet supported:

interface Example {
    exists: true
}

const breaks = { exists: true, doesNotExist: true }

is<Example>(breaks)
// expected: false, received: true

hi @FlorianWendelborn

This is intended behavior: the purpose of the type check is to see if the given object is assignable to the given type.
In your case, the object breaks is assignable to Example, i.e. it fulfills the contract that Example defines as an interface.

Typically you would write this manually yourself in the following way:

function isExample(obj: unknown): obj is Example {
  return typeof obj === 'object' && obj !== null && obj.exists === true;
}

const breaks = { exists: true, doesNotExist: true };
isExample(breaks); // true

In other words: the type check only checks for soundness, but not for completeness. Or: breaks has to be assignable to Example but not Example has to be assignable to breaks.

That being said, it could be possible to add an option to the transformer that makes it check for additional properties and disallows them, something like allowAdditionalProperties: false.
However, I haven't investigated how difficult this would be/if possible/how time consuming.

If you need such a feature let me know, and I'll put it on the list of planned features.

I’d like to use this feature for validating complicated config files. So, if it would be able to detect typos in optional options, that would save me from having to implement this manually.

So, basically, my example isn’t that good. A more fitting example would have someOptionalThing?: string and somePtionalThing: "typo".

I see, that seems like a good use case for this feature. I will add it to the planned feature list, but I think it would take a good amount of time to actually get this implemented.

I will keep this issue updated with progress when I start on it.

PRs are welcome of course!

Hi @FlorianWendelborn

As of version 0.11.0 you can use the option disallowSuperfluousObjectProperties to enable the check for additional properties.
See https://github.com/woutervh-/typescript-is#options for more info.

Writing a unit test for this feature is quite difficult so please let me know if it works for you or not.

Thanks!