ts utility-types ​​​​​​​ 源码解读 aliases-and-guards

原创
08/29 23:02
阅读数 55

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);

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部