-
Notifications
You must be signed in to change notification settings - Fork 45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
TS中is关键字的用法 #149
Comments
is 关键字具有类型保护的作用还能缩小参数范围,常用在类型判断的函数上。因为类型判断函数一般只返回布尔值 true 和 false, typescript 没有办法做进一步的类型推断。 function isString(x: unknown) x is string {
return typeof x === 'string'
}
function f(x: string) {
if (isString(x)) {
x.toLowerCase // 可以被正确推断出来
}
} type Num = 1 | 2 | 3
function isNum (x: unknown): x is Num {
return x === 1 || x === 2 || x === 3
}
function foo(x: number) {
if (isNum(x)) {
switch(x) {
case 1:
case 2:
case 3:
console.log('ok')
case 4: // 这里会飘红
console.log('error')
}
}
} |
is 关键字是一种类型保护,会在运行时检查以确保在某个作用域里的类型。 function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
} |
is 关键字用来对未知类型在具体使用时进行断言或者判断是否是指定类型,可以增加代码的健壮性,避免出现运行时错误。 |
is 关键字一般用于函数返回值类型中,判断参数是否属于某一类型,并根据结果返回对应的布尔类型。 |
ts中有类型保护机制,要定义一个类型保护,我们只需要简单定义一个函数,它的返回值是一个类型谓词
这种写法和isString函数直接返回一个boolean类型的区别在哪里
总结:
|
No description provided.
The text was updated successfully, but these errors were encountered: