3 ms·
Are you familiar with Typescript? If it's possible, could you give me an example of 3 or 4 in Typescript?
by thangngoc89 4y ago
Are you familiar with Typescript? If it's possible, could you give me an example of 3 or 4 in Typescript?
- nivertech 4y agoI don't use TypeScript and I didn't found how to do proper ML-style wrapper types in TypeScript. But I guess one can use type aliases for that: type UserID = { userID: number; }; let validateUserID = function (x: number): UserID? { ... }; Note, that my original example was missing the fact that not every input value is a valid user ID, i.e. the function should return Maybe<UserID>, Option<UserID>, or Result<UserID,SomeErrorType>. In TypeScript one can use optional types xxx? instead.
- thangngoc89 4y agoI was deep into ReasonML/OCaml in the last coupe of years so yeah I missed option/result and the ability to define new type on top of the primitive ones. Your example: type UserID = { id: number; } Would result in more allocations. But I think it's the only way at the moment.
- culi 4y agoyour validation function would probably look more like ```ts const validateUserId = (x: number): x is UserId => {}; ``` for the `UserId` type declaration, I'm actually a little unsure of the best way to go about it. But I feel like using enums, typed string literals, or classes might be better approach. Would be interested if anyone has any thoughts on this
- nikeee 4y agoYou can sue Tagged/Branded types for that: https://medium.com/@KevinBGreene/surviving-the-typescript-ecosystem-branding-and-type-tagging-6cf6e516523d https://medium.com/@KevinBGreene/surviving-the-typescript-ec... It's a simple hack that takes a type and adds an additional field to it. You can then use a User-Defined Type-Guard to ensure a value is valid: https://levelup.gitconnected.com/user-defined-type-guards-in-typescript-fad639e4944f https://levelup.gitconnected.com/user-defined-type-guards-in...
- nivertech 4y agoSo the only change is one line, and there are no additional dependencies? type Brand<K, T> = K & { __brand: T } Looks like a great solution, also the constant syntax is very readable: 10 as USD
- deleted 4y ago[deleted]