I would like to construct a Maybe a
type in typescript a la Haskell:
data Maybe a = Just a | Nothing
It seems like the way to do it in typescript
is:
interface Nothing { tag "Nothing }
type Maybe<T> = T | Nothing
I would like to make a function:
function foo(x : string) : Maybe<T> {
return Nothing
}
akin to:
foo : String -> Maybe a
foo _ = Nothing
However this does not work in typescript
. What is the right way to return a value Nothing
in typescript? I would like to avoid using null
if possible.
___________________________________________________-
Edit: It would be really nice if the function foo
would return a value Nothing
because I would like to pattern match on value constructor later, ie:
case blah blah of
| Just x -> x + x
| Nothing -> "no words"
Estus Flask :
Depending on the case, it can be void, undefined, or ? optional modifier for properties and parameters.\n\nIt's:\n\nfunction foo(x : string) : number | void {\n // returns nothing\n}\n\n\nvoid and undefined types are compatible, but there is some difference between them. The former is preferable for function return types, because the latter requires a function to have return statement:\n\nfunction foo(x : string) : number | undefined {\n return;\n}\n\n\nMaybe can be implemented with generic type. Explicit Nothing type can be implemented with unique symbol:\n\nconst Nothing = Symbol('nothing');\ntype Nothing = typeof Nothing;\ntype Maybe<T> = T | Nothing;\n\nfunction foo(x : string) : Maybe<number> {\n return Nothing;\n}\n\n\nOr a class (private fields can be used to prevent ducktyping):\n\nabstract class Nothing {\n private tag = 'nothing'\n}\ntype Maybe<T> = T | typeof Nothing;\n\nfunction foo(x : string) : Maybe<number> {\n return Nothing;\n}\n\n\nNotice that class types designate class instance type and require to use typeof when a class is referred.\n\nOr an object (if duck typing can be desirable):\n\nconst Nothing: { tag: 'Nothing' } = { tag: 'Nothing' };\ntype Nothing = typeof Nothing;\ntype Maybe<T> = T | Nothing;\n\nfunction foo(x : string) : Maybe<number> {\n return Nothing;\n}\n",
2018-05-28T22:22:03