在 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 没有直接的等价物。相反,你会做什么取决于你将它用于什么:属性、函数参数、变量或函数返回类型......
如果您将它用于属性(在对象/接口中),您可能会使用可选属性,例如:
interface Something {
myProperty?: SomeType;
// ^−−−−− marks it as optional
}
相同的符号适用于函数参数。
对于变量或返回类型,您可以使用带有or的联合类型,例如:undefined
null
let example: SomeType | undefined;
// or
let example: SomeType | null = null;
第一个说 thatexample
可以是SomeType
or undefined
,第二个说它可以是SomeType
or null
。(注意后者需要一个初始化器,否则example
会是undefined
,并且这不是 的有效值SomeType | null
。)