我想Maybe a
在La Haskell的打字稿中构造一个类型:
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
。Nothing
在打字稿中返回值的正确方法是什么?null
如果可能,我想避免使用。
___________________________________________________-
编辑:如果该函数将返回一个值,那将是非常好的,因为我想稍后在值构造函数上进行模式匹配,即:foo
Nothing
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;
}
Maybe
可以用泛型类型实现。显式Nothing
类型可以使用唯一符号来实现:
const Nothing = Symbol('nothing');
type Nothing = typeof Nothing;
type Maybe<T> = T | Nothing;
function foo(x : string) : Maybe<number> {
return Nothing;
}
或一个类(可以使用私有字段来防止鸭嘴兽):
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句