3 ms·
I 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 =
by nivertech 4y ago
I 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