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);
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-2025
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17775114.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2022-10-19 js function chain call implementation principle analysis All In One
2022-10-19 How to get the return value of the setTimeout inner function in js All In One
2021-10-19 vue watch newValue same oldValue bugs All In One
2021-10-19 macOS & VSCode terminal show current git branch All In One
2021-10-19 HTML5 Canvas Tag Cloud All In One
2020-10-19 Iterators & Generators in depth
2020-10-19 Chrome 黑科技