Skip to content
TypeScript

可选链

安全访问深层属性。

#optional-chaining#optional

Code

typescript
interface User {
  profile?: {
    address?: {
      city?: string;
    };
  };
  getName?(): string;
}

const user: User = {};

// Optional chaining avoids errors
const city = user?.profile?.address?.city;
const name = user?.getName?.();

// Array access
const first = arr?.[0];

// Function call
const result = obj?.method?.();

// Combined with nullish coalescing
const display = user?.profile?.address?.city ?? "unknown";