🤔 Did you know TypeScript can generate string unions for you? Template literal types let you build new string literal types and expand them into unions automatically. Here are 3 practical examples: 1. API Endpoints: type Version = 'v1' | 'v2' | 'v3'; type Resource = 'users' | 'posts' | 'comments'; type APIEndpoint = `/api/${Version}/${Resource}`; // Results in 9 possible values... 2. Event Naming Patterns: type EventType = 'click' | 'submit' | 'change'; type Component = 'button' | 'form' | 'input'; type EventName = `on${Capitalize<EventType>}${Capitalize<Component>}`; // 'onClickButton' | 'onClickForm' | ... 3. Property Transformation type User = { firstName: string; lastName: string; email: string; }; type ChangeEvent<T> = `${keyof T & string}Changed`; // 'firstNameChanged' | 'lastNameChanged' | 'emailChanged' #TypeScript #JavaScript #WebDevelopment #SoftwareEngineering
TypeScript String Unions with Template Literal Types
More Relevant Posts
-
JavaScript template literals > string concatenation Before: const msg = 'Hello ' + name + ', you have ' + count + ' messages'; After: const msg = `Hello ${name}, you have ${count} messages`; Readable code is maintainable code. #JavaScript #CleanCode #ES6
To view or add a comment, sign in
-
Dear JS developers ! Did you ever hear about something called Barrel files ? Barrel file is a way where we re-export multiple modules from a single file usually called index.ts or index.js ! Why ? to simplify and centralize imports Here is a detailed example where we have two components, and by creating a barrel file we need a central file called index.ts where we re-export Button and Input then import the needed components wherever we need from a single import. We also can have nested barrel files ! #js #javascript #tricks #react #barrel_file #component #export #import #index
To view or add a comment, sign in
-
-
𝗧𝗮𝗸𝗲 𝗬𝗼𝘂𝗿 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗸𝗶𝗹𝗹𝘀 𝗧𝗼 𝗧𝗵𝗲 𝗡𝗲𝘅𝘁 𝗟𝗲𝘃𝗲𝗹 You use TypeScript to build robust JavaScript applications. But do you use its advanced type features? These features can eliminate bugs and make your code self-documenting. Let's look at a common scenario: user roles in an application. You can use string literals, but this approach has limitations. Advanced types solve these problems at compile time. You can use discriminated unions to represent state machines or API responses. This pattern eliminates null checks and ensures you handle all possible states. You can also use conditional types to create types that change based on other types. Mapped types let you create new types by transforming properties of existing types. TypeScript 4.1 introduced template literal types, bringing type safety to string manipulation. You can combine these concepts into a type-safe API client. To get started, identify one place in your codebase where you're using primitive types. Convert it to use at least one advanced type feature. You'll be surprised how much clarity it brings to your code. Some key takeaways: - Use union types instead of string literals - Use discriminated unions for state management - Add mapped types for common transformations - Let TypeScript work for you to eliminate potential bugs What advanced TypeScript patterns have you found most valuable in your projects? Share your experiences in the comments below! Source: https://lnkd.in/gXJsb-DY
To view or add a comment, sign in
-
💡 Pure vs Impure Functions in JavaScript 🔹 Pure Function Same input → Same output. No side effects. const add = (a, b) => a + b; 🔸 Impure Function Depends on or changes external state. let total = 0; const addToTotal = (v) => total += v; 🚀 Why it matters? Predictable code. Easier testing. Fewer bugs. 👉 Write pure functions whenever possible. #JavaScript #CleanCode #FunctionalProgramming
To view or add a comment, sign in
-
A tale of two JavaScript patterns and the bugs that catch you out 🐛 I've been revisiting the two main ways to create custom objects in JavaScript. Both achieve the same goal. Both have traps. Here's what I found: ES6 Class class Character { constructor(name) { this.name = name this.powers = [] } addPowers(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Methods live outside the constructor, inside the class body. They land on the prototype automatically so every instance shares one copy rather than each carrying its own. Constructor Function function Character(name) { this.name = name this.powers = [] this.addPowers = function(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Easy gotcha: write function addPowers() instead of this.addPowers = and the method becomes a private inner function completely invisible outside the constructor. Your code won't error on creation, it'll just silently fail when you try to call it. The class syntax is cleaner and harder to get wrong. But understanding constructor functions teaches you what's actually happening under the hood and makes legacy codebases far less scary. Worth noting: there is a third way Object.create() but I've not covered it here. It gives you very fine-grained control over the prototype chain, but it's significantly more verbose and rarely the first tool you'd reach for. Both patterns. Both worth knowing. Have you been caught out by either of these? Let me know below 👇 #JavaScript #WebDevelopment #CodingTips #OOP #LearnToCode #JSDevs #SoftwareEngineering
To view or add a comment, sign in
-
🚀 30 Days of JavaScript – Day 16 Starting to build more structured programs using JavaScript. 💡 Today’s Project: Contact Manager This program allows users to: • Add contacts (name & phone) • View stored contacts 🧠 Concepts Used: • functions • arrays of objects • oops • menu-driven logic This helped me understand how to organize code into reusable functions. 🎥 Demo below 👇 Full source code in the First comment. #JavaScript #WebDevelopment #CodingJourney #LearningJavaScript #ProblemSolving
To view or add a comment, sign in
-
𝗧𝗮𝗸𝗲 𝗬𝗼𝘂𝗿 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗸𝗶𝗹𝗹𝘀 𝗧𝗼 𝗧𝗵𝗲 𝗡𝗲𝗫𝗧 𝗟𝗲𝗩𝗲𝗟 TypeScript is now the standard for building robust JavaScript applications. But many developers only use the basic types. - string - number - boolean TypeScript's true power lies in its advanced type features. These features can prevent bugs and make your code more maintainable. Let's look at an example. You're working with a user object that can be in different states. - loading - authenticated - unauthenticated You can use discriminated unions to solve this problem. - type LoadingUser = { status: 'loading'; } - type AuthenticatedUser = { status: 'authenticated'; id: string; name: string; email: string; } - type UnauthenticatedUser = { status: 'unauthenticated'; } - type User = LoadingUser | AuthenticatedUser | UnauthenticatedUser; TypeScript now understands the relationship between status and properties. You can also use conditional types to create types that change based on conditions. - type IsString<T> = T extends string ? true : false; Mapped types let you create new types by transforming properties of existing types. - type Partial<T> = { [P in keyof T]?: T[P]; } Your challenge is to identify one place in your codebase where you're using optional properties to represent different states, and refactor it using discriminated unions. Share your experience in the comments below. Source: https://lnkd.in/gbZSMQTA
To view or add a comment, sign in
-
I was repeating the same logic in every component… and it started getting messy 😅 Yes, seriously. For a long time, I was doing this in React: useEffect(() => { fetchData(); }, []); const [data, setData] = useState(); const [loading, setLoading] = useState(false); Same pattern… in multiple components ❌ ⚠️ This caused: • Code duplication • Hard-to-maintain components • Bigger, messy files 💡 Then I changed my approach: Instead of repeating logic everywhere, 👉 I created a custom hook 🧠 Example: useFetch(url) Handles: • API call • Loading state • Error handling ✅ Result: • Cleaner components • Reusable logic • Easier maintenance 🔥 What I learned: If you’re repeating the same logic… you’re probably missing a custom hook. #ReactJS #FrontendDeveloper #JavaScript #CodingTips #WebDevelopment
To view or add a comment, sign in
-
Catching bugs at 2:00 PM but they don’t wake me up at 2:00 AM. 🛠️ Moving from #JavaScript to #TypeScript wasn’t just a syntax change; it was a shift in confidence. By defining our data structures upfront, we’ve effectively eliminated the "undefined is not a function" errors that used to haunt our production logs. The Difference: In JS, you pass an object and hope the property exists. In TS, the editor won't even let you save the file until you've handled the possibility of it being missing. Example: // JavaScript: The "Finger-Crossing" Method function getUsername(user) { return user.profile.name; // Runtime Error if profile is missing! } // TypeScript: The "Contract" Method interface User { profile?: { name: string }; } function getUsername(user: User) { return user.profile?.name ?? "Guest"; // Type-safe and explicit } The initial setup takes a few extra minutes, but the hours saved in debugging are immeasurable. Have you made the switch yet? Or are you still team Vanilla? 👇 #WebDevelopment #TypeScript #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
Day 12/100 of JavaScript 🚀 Today’s topic: async / await "async" and "await" provide a cleaner way to work with Promises and write asynchronous code that looks like synchronous code 📍Basic example async function getData() { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } 📍With error handling async function getData() { try { const res = await fetch("https://lnkd.in/gCA7VyNQ"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 🔑 Key points : - "async" makes a function return a Promise. - "await" pauses execution until the Promise resolves. - Makes code more readable than ".then()" chaining. async/await simplifies handling asynchronous operations while still using Promises under the hood. #Day12 #JavaScript #100DaysOfCode
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
This approach really showcases how TypeScript can handle complex string combinations so elegantly. The type safety benefits alone make it worth adopting in larger codebases.