Angular中如何将() => number类型转换为number类型?
Hey there! Let's break down this error and fix it quickly.
The error message tells you exactly what's wrong: g.lat isn't a plain number—it's a function that returns a number (that's what () => number means). When you try to assign the function itself to your lat: number variable, TypeScript throws a fit because they're different types.
Here are the solutions to get this working:
1. Call the function to get its return value (most common fix)
Since g.lat is a function that produces a number, just add parentheses to execute it and grab the result:
for (let g of parcelData.geom){ const point = []; let lat : number; lat = g.lat(); // Add parentheses to call the function // Rest of your logic... }
This works because g.lat() runs the function and returns a number, which matches the type you declared for lat.
2. Double-check your type definitions (if this is unexpected)
If you were expecting g.lat to be a number (not a function), you might have a mistake in how you've typed parcelData.geom. For example, if you have an interface for the geometry objects, make sure it's defined correctly:
// Wrong: lat is a function interface GeometryItem { lat: () => number; } // Correct: lat is a number interface GeometryItem { lat: number; }
Updating the interface to reflect the actual data structure will resolve the error without changing your assignment code.
3. Add a type guard for safety (if the type is uncertain)
If there's a chance g.lat could sometimes be a number and sometimes a function, use a type guard to handle both cases safely:
for (let g of parcelData.geom){ const point = []; let lat : number; if (typeof g.lat === 'function') { lat = g.lat(); } else { lat = g.lat; } // Rest of your logic... }
This ensures you handle both scenarios without TypeScript errors.
内容的提问来源于stack exchange,提问作者obar

