DEV Community

Vinayak
Vinayak

Posted on

! and ? in Typescript.

Ever wondered what those mysterious symbols ! and ? do in TypeScript? 🤔 They may be small, but they pack a punch!

Here's how and why to use them.

? - Optional Modifier

Use the ? to mark a property or parameter as optional. It tells TypeScript, "Hey, this field might be undefined."

interface User {     
    name: string;     
    age?: number;   
}
Enter fullscreen mode Exit fullscreen mode

Now age can be defined or left out! 🎯

Why Use "?", well:

  1. Cleaner code: It reduces the need for undefined checks.
  2. Great for flexibility: Perfect for objects where some fields aren’t always needed! Example: Optional query params, form fields, or configuration settings.

! - Non-Null Assertion

The ! is like telling TypeScript, “I know better! This value is definitely NOT null or undefined.”

const element = document.getElementById('app')!;
Enter fullscreen mode Exit fullscreen mode

This assures TypeScript the element exists. But use with care! 🚨

Why Use "!", hmm:

  1. Removes unnecessary null checks when you’re certain a value isn’t null.

⚠️ But... it can be risky if you’re wrong! Use it when you’re in control of initialization or DOM elements that you know exist.

In short:

  • Use ? for flexibility and to safely handle optional properties.
  • Use ! when you're confident a value won't be null/undefined, but be cautious—it can lead to runtime errors if misused.

Basically, these tools help you write cleaner, more maintainable code. đź’ˇ

Top comments (0)