我想用 Haskell 的 typescript 构建一个 Maybe a
类型:
data Maybe a = Just a | Nothing
似乎在 typescript
中的做法是:
interface Nothing { tag "Nothing }
type Maybe<T> = T | Nothing
我想做一个函数:
function foo(x : string) : Maybe<T> {
return Nothing
}
类似于:
foo : String -> Maybe a
foo _ = Nothing
但是这在 typescript
中不起作用。在 typescript 中返回值 Nothing
的正确方法是什么?如果可能,我想避免使用 null
。
_______________________________________________________________________________________________________________________________________________________________________
编辑:如果函数 foo
返回一个 value Nothing
就真的nice 因为我会喜欢稍后在值构造函数上进行模式匹配,即:
case blah blah of
| Just x -> x + x
| Nothing -> "no words"
最佳答案
根据情况,它可以是 void
、undefined
或 ?
属性和参数的可选修饰符。
它是:
function foo(x : string) : number | void {
// returns nothing
}
void
和undefined
类型是兼容的,但它们之间有一些区别。前者更适合函数返回类型,因为后者要求函数具有 return
语句:
function foo(x : string) : number | undefined {
return;
}
也许
可以用泛型来实现。显式 Nothing
类型可以用唯一符号实现:
const Nothing = Symbol('nothing');
type Nothing = typeof Nothing;
type Maybe<T> = T | Nothing;
function foo(x : string) : Maybe<number> {
return Nothing;
}
或者一个类(可以使用私有(private)字段来防止鸭子打字):
abstract class Nothing {
private tag = 'nothing'
}
type Maybe<T> = T | typeof Nothing;
function foo(x : string) : Maybe<number> {
return Nothing;
}
请注意,类类型指定类实例类型,并且在引用类时需要使用 typeof
。
或者一个对象(如果鸭子打字是可取的):
const Nothing: { tag: 'Nothing' } = { tag: 'Nothing' };
type Nothing = typeof Nothing;
type Maybe<T> = T | Nothing;
function foo(x : string) : Maybe<number> {
return Nothing;
}
关于typescript - 也许是 typescript 中的一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573891/