3

For example I have a User type:

type User = {
  name: string;
  city: string;
  email: Email;
  password: Password;
}

I can use string in email but I have some restrictions and that's why I want type Email here. Restrictions are:

  1. It must be of some shape. Only chars a-z are permitted and 2 special chars, . and @. Example, dave.morri[email protected] is valid shape, [email protected] not valid.

  2. It must be of limited length.

Something like:

type Email = /pattern here/

Is it possible to make this type?

5

3 Answers 3

6

The right answer to this is probably a nominal-like type using branding as in @LionelRowe's answer; unless you're dealing with string literal types, so that these email address strings are hardcoded as string literals in your code, there's no way for the compiler to enforce such a constraint. The compiler will only see string.

Even if the compiler knows the exact string literals you are specifying, such as const str = "[email protected]", it's beyond the abilities of TypeScript 4.0 to validate strings like this.


The amazing thing is that it will not be beyond the abilities of TypeScript 4.1, which will introduce template literal types (as implemented in microsoft/TypeScript#40336)... which can actually do operations on string literals.

Unfortunately, as far as I can see, it will be at the edge of TypeScript's abilities. In order to get the compiler to validate that a string is no longer than (say) 32 characters and that it must contain only alphabetic characters, ".", and "@", you'll have to use generics and probably recursive conditional types (also slated for TS4.1 as implemented in microsoft/TypeScript#40002). At every turn you will find yourself avoiding various recursion or combinatorics limits; it's easy to write something that breaks the compiler for strings of just 10 or so characters long. Even when you manage not to hit the limits, the compiler tends to be slow. Type an invalid email and wait 10 seconds before the compiler shows an error. It's a mess and I don't recommend it, at least in TS4.1.

But I love this stuff too much not to do it:

type Lower = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';
type AllowedChars = Lower | '.' | '@'

type RestrictedToChars<T extends string, A extends string, Y = T, N = never> =
  string extends T ? N :
  T extends `${infer F}${infer F}${infer F}${infer F}${infer F}${infer F}${infer R}` ?
  [F] extends [A] ? RestrictedToChars<R, A, Y, N> : N :
  T extends `${infer F}${infer F}${infer F}${infer R}` ?
  [F] extends [A] ? RestrictedToChars<R, A, Y, N> : N :
  T extends `${infer F}${infer R}` ?
  [F] extends [A] ? RestrictedToChars<R, A, Y, N> : N :
  Y

The type RestrictedToChars<T, A, Y, N> takes a string literal T and a union of allowed characters A, and evaluates to: Y if T contains only characters in A, or N if T contains any characters not in A.

type SplitChars<T extends string> = string extends T ? string[] :
  T extends `${infer F1}${infer F2}${infer F3}${infer F4}${infer F5}${infer F6}${infer R}` ? [F1, F2, F3, F4, F5, F6, ...SplitChars<R>] :
  T extends `${infer F1}${infer F2}${infer F3}${infer R}` ? [F1, F2, F3, ...SplitChars<R>] :
  T extends `${infer F1}${infer R}` ? [F1, ...SplitChars<R>] :
  []

type CheckMaxLength<T extends string, L extends number, Y = T, N = never> =
  SplitChars<T>[L] extends undefined ? Y : N;

The type CheckMaxLength<T, L, Y, N> takes a string literal T and a maximum numeric length L, and evaluates to: Y if T is at most L characters long, or N if T is more than L characters long.

You can then define Email<T> as a generic validator on a string literal type T, and make User<T> generic the same way:

type Email<T extends string> = T &
  CheckMaxLength<T, 32, RestrictedToChars<
    `${lowercase T}`, AllowedChars, T, ["Email can only contain alphabet or @ or ."]
  >, ["Email needs to be 32 characters or less"]>;

type User<T extends string> = {
  name: string;
  email: Email<T>;
}

Finally you can see the compiler do the validation:

const user = <T extends string>(user: User<T>) => user;

user({ name: "Dave Morrison", email: "[email protected]" }); // okay
user({ name: "Van Morrison", email: "[email protected]" }); // error!
// ------------------------> ~~~~~
// '["Email can only contain alphabet or @ or ."]'
user({ name: "Jim Morrison", email: "[email protected]" }); // error!
// ------------------------> ~~~~~
// '["Email needs to be 32 characters or less"]'

Exquisitely awful! Again, I do not recommend that you use this. But when TS4.1 is released, it will be technically possible to have the compiler validate strings this way.

Playground link

1
  • Thanks. Yea it's pretty crazy stuff to do for simple thing. I saw 'template literal types', they can be used in nightly builds already. Any way it's one step closer to constrained types and maybe we will get simple and effective way to do that in some time ( that would be huge). Sep 19, 2020 at 16:16
0

The only sort of more specific type than string would be a particular string:

type Email = '[email protected]' | '[email protected]'

That's all you can do, unfortunately. Specific Typescript types are not meant for specifying something about generic user input, other than its type, if the input isn't constrained to a few hard-coded values. For similar reasons, you can't do something like

type BigNum = number > 1000;
3
  • ok, thanks. Is it possible in some other language ? Sep 12, 2020 at 19:35
  • You tagged the question with Typescript, and that's what I know about, so that's the answer I gave. It depends how the string is being used, but strongly-typing a generic user input in any language doesn't make a whole lot of sense IMO. If the data is being put into a DB, you might be able to add a constraint that a column matches a regex. Sep 12, 2020 at 20:42
  • well there is good proposal how to use type refinements. Examples are exactly what i thought it should be. github.com/microsoft/TypeScript/issues/40075 but lead dev at TS marked it too complex and that they don't have plans to do this. Sep 12, 2020 at 20:54
0

Yes, you can do this with an intersection (&) type, but to make it actually type-safe you have to perform runtime checks with an is return type.

type Email = string & { readonly email: unique symbol }

type User = {
    name: string
    email: Email
}

// check with `is` return type
const isValidEmail = (maybeEmail: string): maybeEmail is Email => {
    return maybeEmail.includes('@') && maybeEmail.length < 100
}

const aliceEmail = '[email protected]'

// OK - runtime type safety
if (isValidEmail(aliceEmail)) {
    const alice: User = {
        name: 'Alice',
        email: aliceEmail,
    }
}

// compiles with `as` (bypassing runtime safety)
const bob: User = {
    name: 'Bob',
    email: '[email protected]' as Email,
}

// compile-time error
const charlie: User = {
    name: 'Charlie',
    email: '[email protected]',
}

TypeScript playground

2
  • thanks, of course i can check validity with function but i interested in type that can perform that validation... Sep 13, 2020 at 8:53
  • May I ask what's the use case? If it's for hard-coding some emails, you'd just have to have sure to run them through the check first (you could also use an assert maybeEmail is Email function for this, which throws a runtime error if invalid). If emails come from user input, you're going to need to check them at runtime anyway, and using the intersection type then ensures type safety (as long as you don't deliberately bypass it with as). Sep 13, 2020 at 9:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.