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] Doesn't seem to handle complex union types #40

Closed pipex closed 4 months ago

pipex commented 11 months ago

Describe the bug

I'm trying to create a type that can accept either a positive integer or a numeric string, but type validation is not generating the right code even though each side of the union works by itself. Am I doing something wrong?

type ID =  (number & Int & Min<0>) | (string & Matches<'/\d+/'>);

function validate(user: Assert<ID>) {
    // Your code...
}

validate('1234');

Playground link https://googlefeud.github.io/ts-runtime-checks?code=C4TwDgpgBAkgIlAvFKAKAdgVwLYCMIBOUAZLOsCVALICW6APAAwB8AlFAD5oDOwBdAc0pUAhsADGACwjd6AcgD0AHQAmAagVy2AbgBQugGaZ044DQD26KADcRAGxoqxEVJm6EAXFACC3dwWB6eDYoAG9dFBQFBSgATXNMInFzFQgAOgzdAF99WwcnYBc5AEYAJgBmABY5Vm0gA

Expected behavior

Should compile into something like this

function validate(user) {
     if (typeof user !== "number" || user % 1 !== 0 || user < 0)
         throw new Error("Expected user to be a number, to be an int, to be greater than 0");
     if (typeof user !== "string" || !/d+/.test(user))
        throw new Error("Expected user to be a string, to match /d+/");
 }
GoogleFeud commented 11 months ago

Currently it's not possible to use check types in a union, you could try using the Or check

GoogleFeud commented 4 months ago

Possible in 0.6.0!