I published my first NPM package !
首先,我想精确地说这是我写的第一篇文章,并且我愿意接受任何有关更改和/或改进的建议😉
几个月前,我发现TypeScript并爱上了它。 自从我开始编程以来,我就一直喜欢Javascript,但是由于我的大多数编程教育都是基于Java的,因此缺少静态类型一直是我的真正痛苦。
因此,TypeScript在我的Node.js世界中以圣洁的身份来到我身边! 我只是在Java中缺少TypeScript中的一件事:可选
What is Optional ?
在Java世界中可选的是Java 8中引入的接口,它是Monad模式的抽象。
换句话说,它是您想要的任何类型的包装,用于抽象其无效性。 让我们以一个搜索列表中条目的函数为例
function searchByName<T extends {name: string}>(array: T[], name: string): T | null;
此函数应在数组中搜索具有以下属性的条目:名称 equal to the parameter of the same 名称. If the function doesn't find any entry with the correct 名称, it will return null.
带着可选的类型,您可以这样写:
function searchByName<T extends {name: string}>(array: T[], name: string): Optional<T>;
Why do we need it ?
在我们现代编程语言的世界中,我们拥有一切的抽象。 我们编写的每条指令都是我们无法理解的一些机器代码的多层抽象。 但是,如果我们可以抽象出任何东西,为什么我们还能得到空值几乎每种编程语言中的关键字? (至少我知道的每种语言)
在我看来,空值关键字是编程语言中最抽象的东西,我讨厌使用它。 这就是为什么我错过了可选的我接触TypeScript时界面很多。 因此,我搜索了提供此类功能的图书馆,但没有一个图书馆让我完全满意。
I always wanted to create something that can be reusable for other programmers one of these days, so I created the optionable library (Yeah the optional
name was already taken 😞)
How to use
For now, the optionable library provide the Optionable
interface
interface Optionable<T> {
readonly isPresent: boolean;
get: () => T;
getOrElse: (factory: () => T) => T;
getOrDefault: (defaultValue: T) => T;
getOrThrow: <E extends ErrorConstructor | Error>(error: E) => T;
map: <R>(transformer: (value: T) => R) => R;
}
和3个工厂功能
function of<T>(value: T): Optionable<T>;
function ofNullable<T>(value: T): Optionable<T>;
function empty<T>(): Optionable<T>;
现在让我们举一个例子来展示它是如何使用的。
import { Router, Request, Response } from "express";
import { ofNullable, Optional } from "optionable";
const router = Router();
function findUserById(id: string): Optionable<User> {
return ofNullable(fetchUserTable({ id }));
}
router.get("/user/:id", (req: Request, res: Response) => {
const { id } = request.params;
try {
const user = findUserById(id).orElseThrow(NotFoundError)
} catch(error: NotFoundError) {
res.sendStatus(404);
}
});
这样,您就不必处理空值,并且与传统的空值检查相比,它的写入和读取要干净得多。
这只是您如何使用它的一个示例,但是我鼓励您尽可能多地使用它而不是空值要么未定义。
Closing thoughts
This is the first time I publish a package on NPM so if you want to contribute or have improvements ideas, message me on dev.to or open an issue on the repository, it will be a pleasure ! 😉