原文链接: ts-toolbelt Boolean 模块
上一篇: react 异常捕获
主要思想是自己实现了一套Boolean类型, 使用数字1,0代表真假, 并且使用map和fmt等做了格式化和计算操作
这个是该库最简单的模块, 先从这个入手
代码结构和主要api
用真值表的方式实现逻辑运算
提供format函数, 用于将自定义值转换为其他类型的
但是vscode的提示是按照本身的值做的, 因为用的alias数字的方式, 所以还是有点不太好, 感觉框架内部应该使用这种数字进行封装, 外部依然传入boolean值, 不然和其他库使用的时候会不会出现一些问题
namespace Bool {
type True = 1;
type False = 0;
type Boolean = True | False;
type BooleanOf<B extends boolean> = B extends true ? 1 : 0;
type t7 = BooleanOf<true>; // type t7 = 1
type t8 = BooleanOf<false>; // type t8 = 0
type Fmt = "b" | "s" | "n";
type Format<B extends Boolean, F extends Fmt> = {
0: {
b: false;
s: "false";
n: 0;
};
1: {
b: true;
s: "true";
n: 1;
};
}[B][F];
type t11 = Format<True, "b">; // type t11 = true
type t12 = Format<True, "n">; // type t12 = 1
type t13 = Format<True, "s">; // type t13 = "true"
type Not<B extends Boolean> = {
0: 1;
1: 0;
}[B];
type t1 = Not<True>; // type t1 = 0
type t2 = Not<False>; // type t2 = 1
type And<A extends Boolean, B extends Boolean> = {
0: {
0: 0;
1: 0;
};
1: {
0: 0;
1: 1;
};
}[A][B];
type t3 = And<True, True>; // type t3 = 1
type t4 = And<True, False>; // type t4 = 0
type t5 = And<False, True>; // type t5 = 0
type t6 = And<False, False>; // type t6 = 0
type Or<B extends Boolean> = {
0: {
0: 0;
1: 1;
};
1: {
0: 1;
1: 1;
};
}[B];
type Xor<A extends Boolean, B extends Boolean> = {
0: {
0: 0;
1: 1;
};
1: {
1: 0;
0: 1;
};
}[A][B];
}
自己的封装, 可以看到框架是可以对这层进行抽象的, 不过数字的好处就是运算和处理方便点, 不过类型的语义性也是需要考虑的, 框架多做一点, 开发者就可以偷点懒了
namespace Bool2 {
type True = true;
type False = false;
type Boolean = True | False;
type NumberOf<B extends Boolean> = B extends True ? 1 : 0;
type And<A extends Boolean, B extends Boolean> = {
0: {
0: False;
1: False;
};
1: {
0: False;
1: True;
};
}[NumberOf<A>][NumberOf<B>];
type t1 = And<true, true>; // type t1 = true
type t2 = And<true, false>; // type t2 = false
}