Professional-React-and-Next.js-Course icon indicating copy to clipboard operation
Professional-React-and-Next.js-Course copied to clipboard

ISSUE: CorpComponent - Video 101. Avoiding assertions in typescript for company name.

Open Dev-Dipesh opened this issue 10 months ago • 0 comments

In the video it was recommended to use ! for type assertion since we know better. But in real-world when multiple people are working on a project, mistakes can happen. Last thing we want is our UI to crash because of it. There is a better way to handle this.

Recommended in the video

const companyName = text.split(" ").find((word) => word.includes("#"))!.substring(1);
const newItem = TFeedbackItem = {
    text: text,
    upvoteCount: 0,
    daysAgo: 0,
    companyName: companyName,
    badgeLetter: companyName.substring(0, 1).toUpperCase(),
}

A better approach is to use ? and use || "" for better error handling. Also, badgeLetter can be written much more simply.

const company = text.split(" ").find(word => word.includes("#"))?.substring(1) || "";
const newFeedback: TFeedbackItem = {
    text,      
    company,
    badgeLetter: company[0].toUpperCase(),
    upvoteCount: 0,
    daysAgo: 0,
};

Dev-Dipesh avatar Mar 30 '24 05:03 Dev-Dipesh