一、?(问号)操作符

  在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
}

补充:var b = node[i]?表示,如果node[i]的值为null或者undefined,则b等于undefined,否则b=node[i]。

4、安全链式调用

// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示
// 出错 TS2532: Object is possibly 'undefined'.
return new Error().stack.split('\n');

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

// 以上代码等同以下代码
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
}

3、强制链式调用

// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示
// 出错 TS2532: Object is possibly 'undefined'.
new Error().stack.split('\n');

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

三、Cocos Creator属性装饰器中的|符号

@ccclass
class MyClass {
    @property // JavaScript 原始类型,根据默认值自动识别为 Creator 的浮点数类型。
    index = 0;

    @property(Node) // 声明属性 cc 类型为 Node。当属性参数只有 type 时可这么写,等价于 @property({type: Node})
    targetNode: Node | null = null; // 等价于 targetNode: Node = null!;

注意其中的:

targetNode: Node | null = null; // 等价于 targetNode: Node = null!;



常见错误1:Accessors are only available when targeting ECMAScript 5 and higher

出错命令形式:tsc basic.ts

Cocos Creator编程之Typescript基础语法与常见错误备忘_感叹号

解决办法:tsc test.ts -t es5


引用

https://www.cnblogs.com/gg-qq/p/14649871.html

https://www.zhangshengrong.com/p/JKN8BOzd16/

https://blog.csdn.net/qq_44721831/article/details/121737173

https://blog.51cto.com/u_14184703/5672443