也许是打字稿中的一种类型

chi*_*ro2 3 haskell functional-programming typescript

我想Maybe a在Haskell中构造一个打字稿类型:

data Maybe a = Just a | Nothing
Run Code Online (Sandbox Code Playgroud)

看起来这样做的方法typescript是:

interface Nothing { tag "Nothing }
type Maybe<T> = T | Nothing
Run Code Online (Sandbox Code Playgroud)

我想做一个功能:

function foo(x : string) : Maybe<T> {
    return Nothing
}
Run Code Online (Sandbox Code Playgroud)

类似于:

foo : String -> Maybe a
foo _ = Nothing
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用typescript.什么是Nothing在打字稿中返回值的正确方法?我想null尽可能避免使用.

___________________________________________________-

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

case blah blah of 
    | Just x -> x + x
    | Nothing -> "no words"
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 6

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

它的:

function foo(x : string) : number | void {
    // returns nothing
}
Run Code Online (Sandbox Code Playgroud)

voidundefined类型是兼容的,但它们之间存在一些差异.前者更适用于函数返回类型,因为后者需要一个函数来return声明:

function foo(x : string) : number | undefined {
    return;
}
Run Code Online (Sandbox Code Playgroud)

Maybe可以用泛型类型实现.显式Nothing类型可以使用唯一符号实现:

const Nothing = Symbol('nothing');
type Nothing = typeof Nothing;
type Maybe<T> = T | Nothing;

function foo(x : string) : Maybe<number> {
    return Nothing;
}
Run Code Online (Sandbox Code Playgroud)

或者一个类(私有字段可以用来防止ducktyping):

abstract class Nothing {
    private tag = 'nothing'
}
type Maybe<T> = T | typeof Nothing;

function foo(x : string) : Maybe<number> {
    return Nothing;
}
Run Code Online (Sandbox Code Playgroud)

请注意,类类型指定类实例类型,并且需要在引用typeof类时使用.

或者一个对象(如果可以选择鸭子打字):

const Nothing: { tag: 'Nothing' } = { tag: 'Nothing' };
type Nothing = typeof Nothing;
type Maybe<T> = T | Nothing;

function foo(x : string) : Maybe<number> {
    return Nothing;
}
Run Code Online (Sandbox Code Playgroud)

  • 我列出了所有选项。希望这可以帮助。 (2认同)