ByteGrad / Professional-React-and-Next.js-Course

This repo contains everything you need as a student of the Professional React & Next.js Course by ByteGrad.com
https://bytegrad.com/courses/professional-react-nextjs
111 stars 58 forks source link

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

Open Dev-Dipesh opened 4 months ago

Dev-Dipesh commented 4 months ago

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,
};