You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中出现TypeScript错误TS2339:类型'string'不存在指定属性,请求技术支持

Fixing "Property does not exist on type 'string'" in Your Angular Auth Service

Hey there! I see exactly what's causing that TypeScript error, and it's a common type mismatch issue. Let's break it down and fix it step by step.

What's the Root Cause?

You declared users as a string[] (array of strings), but the data you're pulling from localStorage is actually an array of user objects (with userName and password properties). TypeScript strictly enforces the type you defined, so it thinks every u in your find() callback is a string—and strings don't have userName or password properties. That's why you're getting the ts(2339) error.

Step-by-Step Fix

Here's how to resolve this properly:

  1. Define a User Type
    First, create an interface to describe the structure of your user objects. This tells TypeScript exactly what properties to expect from each user entry.

  2. Correct the users Array Type
    Change the type of users from string[] to your new user type array, matching the actual data structure.

  3. Fix LocalStorage Parsing
    Your original code uses || '{}' which would parse to an empty object if localStorage has no "Users" entry—we need to parse to an empty array instead to keep the type consistent.

Full Fixed Code

import { Injectable } from '@angular/core';

// Define the structure of a User object
interface User {
  userName: string;
  password: string;
  // Add any other user properties you might have (e.g., id, email)
}

@Injectable({ providedIn: 'root' })
export class AuthService {
  constructor() { }

  authUser(user: User) { // Replace 'any' with our User type for better type safety
    let users: User[] = [];
    const storedUsers = localStorage.getItem('Users');
    
    if (storedUsers) {
      users = JSON.parse(storedUsers);
    }

    // Now TypeScript knows 'u' is a User, so accessing userName/password is valid
    return users.find(u => u.userName === user.userName && u.password === user.password);
  }
}

Bonus Tips for Better Code

  • Avoid any Type: Replacing user: any with user: User gives you TypeScript's full type-checking benefits—you'll catch typos or missing properties early in development.
  • Security Note: Never store plaintext passwords in localStorage! This is a huge security risk. In a real app, send credentials to your backend for validation and store a secure token (like JWT) instead.
  • Robust Parsing: If you want to handle edge cases where localStorage has invalid data, add a try/catch block around JSON.parse() to prevent unexpected crashes.

内容的提问来源于stack exchange,提问作者Paul Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:32:49