! and ? in Typescript.

vinayak00017

Vinayak

Posted on October 17, 2024

! 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. đź’ˇ

đź’– đź’Ş đź™… đźš©
vinayak00017
Vinayak

Posted on October 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

! and ? in Typescript.
webdev ! and ? in Typescript.

October 17, 2024

Apa itu TypeScript?
webdev Apa itu TypeScript?

November 21, 2023

Coding Concepts - Generics
webdev Coding Concepts - Generics

June 21, 2018