TypeScript的非空断言操作符(感叹号)
typescript 操作符 断言 非空 感叹号
2023-09-14 09:02:58 时间
x! 将从 x 值域中排除 null 和 undefined.
看个例子:
myFunc = (maybeString: string | undefined | null) => {
const onlyString: string = maybeString; // Error
const ignoreUndefinedAndNull: string = maybeString!; // Ok
}
myFunc2 = (onlyString: string) => {
const a: string = onlyString;
}
constructor() {
this.myFunc('jerry');
this.myFunc(undefined);
this.myFunc2(undefined);
this.myFunc2(null);
}
没有编译错误,也能正常运行:
我的Angular版本:
测试出的结果和这篇文章细数 TS 中那些奇怪的符号里提到的不一致:
更多Jerry的原创文章,尽在:“汪子熙”:
相关文章
- [Typescript] 130. Hard - Replace Union
- [Typescript] 107. Medium - FindIndex
- [TypeScript] Labelled tuple type
- [TypeScript] Understand lookup types in TypeScript
- [Typescript] Function overload: For default value arguement
- [React Typescript] Discriminated unions in components props
- [Typescript] 110. Hard - Union to Tuple
- [Typescript] 91. Hard - Union to Intersection
- [Typescript] 87. Medium - DeepMutable
- [Typescript] 71. Medium - Trunc
- [Typescript] 66. Medium - IsTuple
- [Typescript] Tips: Create autocomplete helper which allows for arbitrary values
- [Typescript + React] Tip: Use generics in React to make dynamic and flexible components
- [Typescript] 23. Medium - Promise.all
- [Typescript] Pick partially object type with indexed access types
- [TypeScript] Increase TypeScript's type safety with noImplicitAny
- [RxJS] Add debug method to Observable in TypeScript
- typescript ts keyof操作符使用示例
- 什么是 TypeScript 变量的 declared type
- TypeScript Non-null Assertion Operator 非空断言操作符 - 感叹号
- 巧用 TypeScript Literal Types 模拟枚举类型
- TypeScript里的类型合并操作符&