美文网首页
TS中的问号 ? 与感叹号 ! 是什么意思

TS中的问号 ? 与感叹号 ! 是什么意思

作者: 合肥黑 | 来源:发表于2021-04-28 09:56 被阅读0次

参考
巧用ES系列4: TypeScript中的问号 ? 与感叹号 ! 是什么意思?

一、什么是 ?(问号)操作符?

在TypeScript里面,有4个地方会出现问号操作符,他们分别是

1.三元运算符
// 当 isNumber(input) 为 True 时返回 ? : 之间的部分; 
// isNumber(input) 为 False 时返回 : ; 之间的部分
const a = isNumber(input) ? input : String(input);
2.可选参数
// 这里的 ?表示这个参数 field 是一个可选参数
function getUser(user: string, field?: string) {
}
3.成员
// 这里的?表示这个name属性有可能不存在
class A {
  name?: string
}

interface B {
  name?: string
}
4.安全链式调用
// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示
// 出错 TS2532: Object is possibly 'undefined'.
return new Error().stack.split('\n');

// 我们可以添加?操作符,当stack属性存在时,调用 stack.split。
// 若stack不存在,则返回空
return new Error().stack?.split('\n');

// 以上代码等同以下代码, 感谢 @dingyanhe 的监督
const err = new Error();
return err.stack && err.stack.split('\n');
二、什么是!(感叹号)操作符?

在TypeScript里面有3个地方会出现感叹号操作符,他们分别是

1.一元运算符
// ! 就是将之后的结果取反,比如:
// 当 isNumber(input) 为 True 时返回 False; 
// isNumber(input) 为 False 时返回True
const a = !isNumber(input);
2.成员
// 因为接口B里面name被定义为可空的值,但是实际情况是不为空的,
// 那么我们就可以通过在class里面使用!,重新强调了name这个不为空值
class A implemented B {
  name!: string
}

interface B {
  name?: string
}

这里可以参考ts 更严格的类属性检查

Typescript 2.7 引入了一个新的控制严格性的标记 –strictPropertyInitialization, 这个参数在 tsconfig.ts 中来配置

"strictNullChecks": true
"strictPropertyInitialization": true

作用

  • 使用这个标记会确保类的每个实例属性都会在构造函数里或使用属性初始化器赋值。
  • 它会明确地进行从变量到类的实例属性的赋值检查

举例

class C {
  foo: number;
  bar = "hello";
  baz: boolean;
  constructor() {
    this.foo = 42;
  }
}

上述代码,首先编辑器会报错: 属性“baz”没有初始化表达式,且未在构造函数中明确赋值。ts(2564)
其次在编译报错:error TS2564: Property 'baz' has no initializer and is not definitely assigned in the constructor.

两种都告诉开发者,应该给 baz 显示赋值,但是某种情况下,在初始化的时候我们并不想赋值,更期望是 undefined,而后再去赋值,此时 !: 就派上用场了。

在上述代码中 属性 baz 冒号之前加上 ! ,这样就不会报错了

class C {
  foo: number;
  bar = "hello";
  baz!: boolean;
  constructor() {
    this.foo = 42;
  }
}
3.强制链式调用
// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示
// 出错 TS2532: Object is possibly 'undefined'.
new Error().stack.split('\n');

// 我们确信这个字段100%出现,那么就可以添加!,强调这个字段一定存在
new Error().stack!.split('\n');

相关文章

网友评论

      本文标题:TS中的问号 ? 与感叹号 ! 是什么意思

      本文链接:https://www.haomeiwen.com/subject/ypgklltx.html