Using optional chaining operator for object property access

前端 未结 2 753
不思量自难忘°
不思量自难忘° 2021-01-03 17:52

TypeScript 3.7 now supports the optional chaining operator. Hence, you can write code such as:

const value = a?.b?.c;

I.e., you can use thi

相关标签:
2条回答
  • The Optional Chaining operator is ?.

    Here are some examples for nullable property and function handling.

    const example = {a: ["first", {b:3}, false]}
    
    // Properties
    example?.a  // ["first", {b:3}, false]
    example?.b  // undefined
    
    // Dynamic properties ?.[]
    example?.a?.[0]     // "first"
    example?.a?.[1]?.a  // undefined
    example?.a?.[1]?.b  // 3
    
    // Functions ?.()
    null?.()                // undefined
    validFunction?.()       // result
    (() => {return 1})?.()  // 1
    

    Bonus: Default values

    ?? (Nullish Coalescing) can be used to set a default value if undefined or null.

    const notNull = possiblyNull ?? defaultValue
    const alsoNotNull = a?.b?.c ?? possiblyNullFallback ?? defaultValue
    
    0 讨论(0)
  • 2021-01-03 18:42

    When accessing a property using bracket notation and optional chaining, you need to also have a dot in addition to the brackets:

    const value = a?.[b]?.c;
    

    This is the syntax that was adopted by the TC39 proposal, because otherwise it's hard for the parser to figure out if this ? is part of a ternary expression or part of optional chaining.

    0 讨论(0)
提交回复
热议问题