1

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

我将如何在打字稿中建模相同的东西?

4

2 回答 2

1

也许,是这样的:

export type None = never;

export type Some<A> = A;

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

如果你对使用 ts 的函数式编程感兴趣,你可以看看fp-ts

于 2020-10-23T10:23:06.237 回答
1

TypeScript 没有直接的等价物。相反,你会做什么取决于你将它用于什么:属性、函数参数、变量或函数返回类型......

如果您将它用于属性(在对象/接口中),您可能会使用可选属性,例如:

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

相同的符号适用于函数参数。

对于变量或返回类型,您可以使用带有or的联合类型,例如:undefinednull

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

第一个说 thatexample可以是SomeTypeor undefined,第二个说它可以是SomeTypeor null。(注意后者需要一个初始化器,否则example会是undefined,并且这不是 的有效值SomeType | null。)

于 2020-10-23T10:23:38.573 回答