Typescript 中的操作符 ? !

289 阅读1分钟

! 操作符是干啥的?

告诉编译器,当前数据不为“空”

    let some = string | undefine;
    ...
    console.log(some!.length)

这里的“空” 指 null undefine

? 操作符是干啥的?

编译器帮你判断“空”

// Before
if (foo && foo.bar && foo.bar.baz) {
    // ...
}

// After-ish
if (foo?.bar?.baz) {
    // ...
}
// 它可以判断 数组 和 函数 是否是“空”, 形式上 使用“对象”式
/**
 * Get the first element of the array if we have an array.
 * Otherwise return undefined.
 */
function tryGetFirstElement<T>(arr?: T[]) {
    return arr?.[0];
    // equivalent to
    //   return (arr === null || arr === undefined) ?
    //       undefined :
    //       arr[0];
}

async function makeRequest(url: string, log?: (msg: string) => void) {
    log?.(`Request started at ${new Date().toISOString()}`);
    // roughly equivalent to
    //   if (log != null) {
    //       log(`Request started at ${new Date().toISOString()}`);
    //   }

    const result = (await fetch(url)).json();

    log?.(`Request finished at at ${new Date().toISOString()}`);

    return result;
}

这里的“空” 指 null undefine 相关链接

?? 符号是干啥的?

理解为如果为“空”则使用.

let x = foo ?? bar();
// equivalent to
let x = (foo !== null && foo !== undefined) ?
    foo :
    bar();

它和 || 区别

  • ?? 对“空” 的定义 有 null undefine
  • || 对“空”的定义 有 null undefine 0 NaN ""