TypeScript报错:Cannot read property 'filter' of undefined 求助
Hey there, let's dig into why you're seeing this ERROR TypeError: Cannot read property 'filter' of undefined and how to fix it.
错误原因
Looking at your code, you've declared several array properties like contrat: Contrat[]; and gpss: GPS[]; but you haven't initialized them with a value. In TypeScript (and JavaScript), variables declared without an initial value default to undefined. When you try to call filter() on this.contrat or any of these arrays, you're essentially trying to run a method on undefined—which doesn't have any properties or methods, hence the error.
Another possible scenario: if these arrays are supposed to be populated with data from an asynchronous source (like an API call), you might be calling getProductName() before the data has finished loading. That means the arrays are still undefined when the method runs.
解决方法
Here are a few straightforward fixes to resolve this:
Initialize arrays as empty arrays
The simplest fix is to set each array to an empty array when you declare it. This ensures the arrays always exist (even if they have no data yet) and have access to thefiltermethod. Update your property declarations like this:contrat: Contrat[] = []; gpss: GPS[] = []; homeboxp: HomeboxP[] = []; sensors: Sensors[] = []; homebox: Homebox[] = [];Add null/undefined checks (recommended for safety)
If there's a chance your arrays might stayundefinedin some cases (like waiting for async data), use optional chaining (?.) to safely access thefiltermethod, and fall back to an empty array if the original is undefined:const [filteredProd] = this.contrat?.filter(pt => pt.contrat_id === productid) || []; const [filteredProdG] = this.gpss?.filter(pt => pt.gps_id === productid) || []; const [filteredProdhbp] = this.homeboxp?.filter(pt => pt.homeboxpackage_id === productid) || []; const [filteredProdh] = this.homebox?.filter(pt => pt.homebox_id === productid) || [];This way, if the array is
undefined, the expression will return an empty array instead of throwing an error.Wait for async data to load before calling the method
If your arrays are populated via an async operation (like fetching data from a server), make sure you only callgetProductName()after the data has been successfully assigned to the arrays. For example, in Angular you'd put the method call inside thesubscribecallback of your HTTP request; in React, you'd useuseEffectto trigger the method when the array state updates.
内容的提问来源于stack exchange,提问作者user9515832

