TypeScript type predicates All In One

发布时间 2023-10-19 16:59:49作者: xgqfrms

TypeScript type predicates All In One

类型谓词 / 类型断言

Narrowing / 类型收窄

type predicates

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

To define a user-defined type guard, we simply need to define a function whose return type is a type predicate:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates

tsc

# local ?
# vscode ?
$ npm install -D typescript
$ npm install -D ts-node

$ npx tsc -v
# Version 5.2.2

# ts-node ✅
$ yarn dev
$ npm run dev

demos

export {};

// is 类型谓词
// function isString(str: any): str is string {
// function isString(str: unknown): str is string {
// ❓ Parameter 'str' implicitly has an 'any' type, but a better type may be inferred from usage.ts(7044)
function isString(str): str is string {
  return typeof str === 'string';
}

function isNumber(num: number): boolean {
  return typeof num === 'number';
}

function test(x: unknown) {
  if (isString(x)) {
    console.log(`string ✅`);
  }
  // ❌ Argument of type 'unknown' is not assignable to parameter of type 'number'.ts(2345)
  // if (isNumber(x)) {
  //   console.log(`number ✅`);
  // }
  if (isNumber(x as number)) {
    console.log(`number ✅`);
  }
}

test(`str`);
test(2023);

image

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

predicate

英 ['predɪkət] 美 ['predɪkət]
释义:

  1. vt. 断言,断定; 宣布,宣讲; 使基于
  2. vi. 断言,断定
  3. n. 谓语; 述语

https://www.iciba.com/word?w=predicate

主谓宾 / 主语 谓语 宾语

我在 看 书
我在 钓 鱼
I'm fishing

主语 谓语 宾语

functions overload

函数重载

https://www.typescriptlang.org/docs/handbook/2/functions.html#overload-signatures-and-the-implementation-signature

refs

https://stackoverflow.com/questions/40081332/what-does-the-is-keyword-do-in-typescript



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!