TypeScript type predicates All In One
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
Type Guards
A type guard
is some expression
that performs a runtime check
that guarantees
the type
in some scope
.
To define a type guard, we simply need to define a function whose return type
is a type predicate
:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
pet
is Fish
is our type predicate in this example.
A predicate takes the form parameterName
is Type
, where parameterName
must be the name
of a parameter from the current function signature
.
Any time isFish
is called with some variable, TypeScript will narrow
that variable to that specific type
if the original type
is compatible
.
// both calls to 'swim' and 'fly' are now okay.
let pet = getSmallPet();
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
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);
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
predicate
英 ['predɪkət
] 美 ['predɪkət
]
释义:
- vt.
断言
,断定; 宣布,宣讲; 使基于 - vi. 断言,断定
- n.
谓语
; 述语
https://www.iciba.com/word?w=predicate
主谓宾 / 主语 谓语 宾语
我在 看 书
我在 钓 鱼
I'm fishing
主语 谓语 宾语
functions overload
函数重载
refs
https://stackoverflow.com/questions/40081332/what-does-the-is-keyword-do-in-typescript
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17775114.html
未经授权禁止转载,违者必究!