与ReasonML的选项类型等效的打字稿是什么?

问题描述

在ReasonML中,option类型是一种变体,可以是Some('a)None

我该如何在打字稿中为同一事物建模?

解决方法

也许是这样的:

export type None = never;

export type Some<A> = A;

export type Option<A> = None | Some<A>

如果您对使用ts进行函数编程感兴趣,可以看看fp-ts

,

TypeScript没有直接等效项。相反,您要做什么取决于您将其用于什么:属性,函数参数,变量或函数返回类型...

如果将其用于属性(在对象/接口中),则可能使用optional properties,例如:

interface Something {
   myProperty?: SomeType;
//           ^−−−−− marks it as optional
}

相同的符号适用于功能参数。

对于变量或返回类型,您可以将union typeundefinednull一起使用,例如:

let example: SomeType | undefined;
// or
let example: SomeType | null = null;

第一个说example可以是SomeTypeundefined类型,第二个说它可以是SomeTypenull。 (请注意,后者需要一个初始化程序,因为否则example将是undefined,并且对于SomeType | null来说不是有效值。)