如何将下述金额找零逻辑提取并转换为TypeScript?
Hey there! Since you're new to TypeScript, let's walk through extracting and converting your existing HTML/JS change logic into type-safe, clean TypeScript. We'll split this into two clear parts: the core change-calculation logic (as a reusable function) and the DOM interaction code (to hook it up to your inputs).
First, Fix & Extract the Core Change Logic
Your original JavaScript has a few small inconsistencies (like uninitialized variables and unused arrays) that we'll clean up while converting. The core idea is calculating how many of each denomination fit into the total amount, then updating the remaining value for the next denomination.
We'll start with a TypeScript interface to define our result structure—this makes our code self-documenting and catches type errors early:
// Define a type for our change result to enforce consistent structure interface ChangeResult { twothousand: number; fivehundred: number; hundred: number; } // Core reusable function to calculate change (pure, no side effects) function calculateChange(total: number): ChangeResult { let remaining = total; // Calculate count for each denomination const twothousand = Math.floor(remaining / 2000); remaining = remaining % 2000; const fivehundred = Math.floor(remaining / 500); remaining = remaining % 500; const hundred = Math.floor(remaining / 100); return { twothousand, fivehundred, hundred }; }
Now, Hook It Up to the DOM (TypeScript Style)
Next, we'll rewrite the DOM interaction code with TypeScript's type safety. We'll handle possible null values (since getElementById might not find an element) and validate user input to avoid errors:
// Wait for the DOM to fully load before accessing elements document.addEventListener('DOMContentLoaded', () => { // Get elements with type assertions (we know they exist in our HTML) const amtInput = document.getElementById('amt') as HTMLInputElement; const btn = document.getElementById('btn') as HTMLButtonElement; // Get span elements for displaying results const spans = document.querySelectorAll('span') as NodeListOf<HTMLSpanElement>; // Map spans to their corresponding denomination (matches your HTML order) const denominationKeys: Array<keyof ChangeResult> = ['twothousand', 'fivehundred', 'hundred']; btn.addEventListener('click', () => { // Convert input value to a number, handle empty/invalid input const inputValue = amtInput.value.trim(); const total = inputValue ? parseInt(inputValue, 10) : 0; if (isNaN(total) || total < 0) { alert('Please enter a valid positive number'); return; } // Calculate change using our core function const change = calculateChange(total); // Update each span with the result (matches your original append logic) spans.forEach((span, index) => { const key = denominationKeys[index]; span.textContent = `${span.textContent || ''}${change[key]}`; }); }); });
Key Improvements Over the Original Code
- Type Safety: Interfaces and type assertions prevent runtime errors (like trying to call methods on a null element).
- Reusable Logic: The
calculateChangefunction is pure and can be tested independently without relying on the DOM. - Input Validation: We handle empty or non-numeric input to avoid NaN issues.
- Cleaner Structure: Removed unused variables (like
changeArrayfrom your original code) and made the flow easier to follow.
Your Original HTML Works As-Is
No changes needed to your HTML—it pairs perfectly with this TypeScript code:
<input type="text" id="amt"/> <input type="button" value="change" id="btn"/> <br/> twothousand: <span></span><br/> fivehundred: <span></span><br/> hundred: <span></span><br/>
Just remember to compile your TypeScript to JavaScript (using tsc or a bundler like Vite/Webpack) before running it in the browser!
内容的提问来源于stack exchange,提问作者Abhishek Gautam

