Skip to content
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

Open
su37josephxia opened this issue Mar 11, 2022 · 5 comments
Open

TS中is关键字的用法 #149

su37josephxia opened this issue Mar 11, 2022 · 5 comments

Comments

@su37josephxia
Copy link
Owner

No description provided.

@zcma11
Copy link

zcma11 commented Mar 12, 2022

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')
    }
  }
}

@7TingYu
Copy link

7TingYu commented Mar 12, 2022

is 关键字是一种类型保护,会在运行时检查以确保在某个作用域里的类型。

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

if (isFish(pet)) {
    pet.swim();
}
else {
    pet.fly();
}

@zhenyuWang
Copy link

is 关键字用来对未知类型在具体使用时进行断言或者判断是否是指定类型,可以增加代码的健壮性,避免出现运行时错误。

@partiallove
Copy link

is 关键字一般用于函数返回值类型中,判断参数是否属于某一类型,并根据结果返回对应的布尔类型。
通过 is 关键字将类型范围缩小为 string 类型,这也是一种代码健壮性的约束规范
is 关键字经常用来封装”类型判断函数”,通过和函数返回值的比较,从而缩小参数的类型范围,所以类型谓词 is 也是一种类型保护。

@miracle-dx
Copy link

ts中有类型保护机制,要定义一个类型保护,我们只需要简单定义一个函数,它的返回值是一个类型谓词

function isString(x: any): x is string {
  return typeof x === 'string';
}
function isStringy(x: any): boolean {
  return typeof x === 'string';
}

这种写法和isString函数直接返回一个boolean类型的区别在哪里

使用is关键字

function example(foo: any) {
  if (isString(foo)) {
    let len = foo.length;
    let m = foo.toExponential(2); // 编译时就报错,运行时也报错
  }
  let m = foo.toExponential(2); // 编译时不报错,运行时报错
}

使用boolean

function exampley(foo: any) {
  if (isStringy(foo)) {
    let len = foo.length;
    let m = foo.toExponential(2); // foo的类型是any,编译时不报错,但是string没有toExponential这个属性运行时也报错
  }
  let m = foo.toExponential(2); // 编译时不报错,运行时报错
}

总结:

  • ts使用类型保护,进一步缩小了变量的类型,例子中使用is关键字将any收缩到了string类型
  • 类型保护的作用域仅在if后的块级作用域中有效

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants