https://github.com/piotrwitek/utility-types
bigInt需要es2020的支持
Primitive / isPrimitive
js原始类型已经判断一个对象的类似是不是原始类型
// js原始类型, 面试常考...
export type Primitive =
| string
| number
| bigint
| boolean
| symbol
| null
| undefined;
function log(msg: Primitive[]) {
console.log(...msg);
}
// log([{ a: 1 }]);
// 正常输出log
log([1, "1", "a", null, undefined, 12n]);
export const isPrimitive = (val: unknown): val is Primitive => {
if (val === null || val === undefined) {
return true;
}
switch (typeof val) {
case "string":
case "number":
case "bigint":
case "boolean":
case "symbol": {
return true;
}
default:
return false;
}
};
console.log(isPrimitive(0)); // true
console.log(isPrimitive("a")); // true
console.log(isPrimitive({ a: 1 })); // false
Falsy / isFalsy
假值以及判断是不是假值
export type Falsy = false | "" | 0 | null | undefined;
export const isFalsy = (val: unknown): val is Falsy => !val;
const falseList: Falsy[] = [];
falseList.push(0);
falseList.push("");
falseList.push(null);
falseList.push(undefined);
function push<T>(v: T) {
if (isFalsy(v)) {
falseList.push(v);
} else {
console.log("v为真值", v);
}
}
push(0);
push(1);
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/4535245