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

时间秒杀一切 提交于 2020-09-25 10:58:58

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!