1

I am trying to create a type that represents a UUID in TypeScript. I'm new to TS but found this post that describes how to make a similar solution. However, when I use four (three is fine) of the same type, it causes this error. I can't find any solution because it appears imports or wrong TS versions in VS Code cause most. This is just a simple .ts file and I've already switched my VS Code TS versions from the workspace and vice versa. The code in question is below:

type uuidChar = 'q' | 'w' | 'e' | 'r' | 't' | 'y' | 'u' | 'i' | 'o' | 'p' | 'a' | 's' | 'd' | 'f' | 'g' | 'h' | 'j' | 'k' | 'l' | 'z' | 'x' | 'c' |
'v' | 'b' | 'n' | 'm' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0';

type uuid = `${uuidChar}-${uuidChar}-${uuidChar}-${uuidChar}`

I want to make a type for an object field that represents a UUID from the crypto library and I couldn't find any types already made.

Thank you in advance!

Jacob Bruce
  • 55
  • 2
  • 10
  • You should include the error in your question. I am assuming it is `Expression produces a union type that is too complex to represent.` ? – Hunter McMillen Dec 29 '22 at 16:02
  • Yes, sorry I thought if I included It in the title it would be enough, sorry about that – Jacob Bruce Dec 29 '22 at 17:21
  • 1
    no worries, tbh I missed it in the title :). You could attempt this with a recursive type like in [this answer](https://stackoverflow.com/questions/72922880/typescript-type-to-check-if-the-string-contains-only-specific-characters) but there is an existing [`@types/uuid`](https://www.npmjs.com/package/@types/uuid) package that is already well-used and tested. – Hunter McMillen Dec 29 '22 at 17:45
  • I saw that type when searching, but I wasn't sure if that would work with the Crypto library, I'm just new to all this. – Jacob Bruce Dec 29 '22 at 17:56
  • Could you explain why you want such a type? Are you going to have UUID string literals in your TypeScript code at compile time or do they only exist at runtime? The answer will strongly drive the solution. – jcalz Dec 29 '22 at 19:22
  • They're being attached to a class instance, so realistically just runtime. – Jacob Bruce Dec 29 '22 at 22:23
  • 1
    Types don't exist at runtime. You could use the library to validate a string at runtime though: https://github.com/uuidjs/uuid#uuidvalidatestr – Hunter McMillen Dec 29 '22 at 22:53

0 Answers0