可能是打字稿中的类型

xiaolingxiao

我想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

但是,这不适用于typescriptNothing在打字稿中返回值的正确方法是什么null如果可能,我想避免使用

___________________________________________________-

编辑:如果该函数将返回一个值,那将是非常好的因为我想稍后在值构造函数上进行模式匹配,即:foo Nothing

case blah blah of 
    | Just x -> x + x
    | Nothing -> "no words"
那将是烧瓶

根据不同的情况下,也可以是voidundefined?对属性和参数可选修饰符。

它的:

function foo(x : string) : number | void {
    // returns nothing
}

voidundefined类型兼容,但是它们之间存在一些差异。对于函数返回类型,前者更可取,因为后者需要一个函数具有以下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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章