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

原文链接: ts utility-types 源码解读 aliases-and-guards

上一篇: react createPortal 弹出框简单实现

下一篇: ts utility-types ​​​​​​​ 源码解读 Union operators

https://github.com/piotrwitek/utility-types

bigInt需要es2020的支持

up-8c134b711be329980a401041a9f50b03698.png

Primitive / isPrimitive

js原始类型已经判断一个对象的类似是不是原始类型

up-20fa7ad3b85f3c56461bba756abc519c364.png

// 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

假值以及判断是不是假值

up-cd36dc712ee7c523eac4879be8d75153c81.png

up-f1e60889ac19e4d71c1a8a8dc8cca17cd88.png


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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值