rhys-vdw / ts-auto-guard

Generate type guard functions from TypeScript interfaces
MIT License
500 stars 55 forks source link

Some template literals types will break the generator #157

Open SamuelCharpentier opened 3 years ago

SamuelCharpentier commented 3 years ago

As soon as you use a "wildcard" in a template literal string like `${string}`, the generator breaks down.

For example, if you have an email type like this:

type Email = `${string}@${string}.${string}`

the generated typeguard looks like this:

import { Email } from "./Email";

export function Email(obj: any, _argumentName?: string): obj is Email {
    return (
        typeof obj === "`${string}@${string}.${string}`"
    )
}

and that don't work as the typeof obj would be "string".

rhys-vdw commented 3 years ago

Oh yeah, that's a non-trivial fix. This project was created before template literal types were a thing. We'd need some sort of regex validator to do it properly, but for now falling back to a regular string check and logging an error would be best.

I'll accept a PR that provides either fix.

elliot-huffman commented 3 months ago

After researching this, I don't think a complex validator is necessary. All template strings are always string in the typeof key word. Even if the values are null, undefined, numbers, objects, etc. in the template string itself. I think it is safe to set the logic to the following: "If a template string is detected, validate the stored type is a string."

I think validating the content of the string would be where the regex is necessary, the object type (contain of the string content) will always be string though.