typescript - 也许是 typescript 中的一种类型

标签 typescript haskell functional-programming

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

最佳答案

根据情况,它可以是 voidundefined? 属性和参数的可选修饰符。

它是:

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

voidundefined 类型是兼容的,但它们之间有一些区别。前者更适合函数返回类型,因为后者要求函数具有 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/

相关文章:

javascript - Angular 2 : select not updating with selected value in ion-select Ionic 2?

Haskell 函数 iter 结果

haskell - 无限列表上的折叠行为

javascript - 了解 Ramda.js

java - Spring接口(interface)转换器

使用 Promise 的 TypeScript 异步类型保护

typescript - 是否可以让函数接受类实例,但不接受普通对象?

class - 如果 Haskell 的编译器总是需要用 "::Int"指定多态函数的多态参数,为什么 "show 2"是合法的

string - 如何在haskell中组合两个字符串中的字母

typescript - 将传单标记扩展转换为 Typescript