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

使用TypeScript+React时,导入枚举为何出现未定义属性报错?

Fix: "Cannot read property 'Customer' of undefined" in React + TypeScript Project

Let's break down this error first — it's telling you that the Roles variable you're trying to access is undefined, so when you try to get Roles.Customer, JavaScript throws that error. Here's how to fix it step by step:

1. Double-check how Roles is exported in ../common/utils

This is the most common culprit. Let's verify the export style in your utils.ts (or matching filename):

Case 1: Named Export

If you're using a named export, your utils file should look like this:

export const Roles = {
  Customer: 'customer',
  // Add other roles here
};

Your current import import { Roles } from '../common/utils' is correct here — just make sure the spelling (including capitalization!) matches exactly (TypeScript is case-sensitive).

Case 2: Default Export

If Roles is exported as a default export in utils:

const Roles = {
  Customer: 'customer',
  // Add other roles here
};
export default Roles;

You need to update your import statement to remove the curly braces, since default exports don't use them:

import Roles from '../common/utils';

Using { Roles } with a default export will result in undefined for the Roles variable.

2. Verify the file path is correct

Typos or wrong directory levels here are easy to miss:

  • Did you misspell the folder or filename? (e.g., util instead of utils)
  • Is the relative path accurate? (e.g., maybe it should be ../../common/utils if your current file is nested one level deeper)
  • If you're using a less common file extension (like .tsx instead of .ts), try adding the full extension to the import (create-react-app usually handles this, but it's worth testing).

3. Check for circular imports

If your ../common/utils file imports the component/file where you define defaultUser, you've got a circular dependency. This can cause modules to load before their values are initialized, leading to undefined for Roles. To fix this, move the Roles definition to a separate, independent file that neither imports nor is imported by your user details file.

4. Confirm enum definitions (if applicable)

If Roles is a TypeScript enum, make sure it's exported correctly:

export enum Roles {
  Customer = 'Customer',
  // Other enum values
}

Your existing named import should work here, but again, double-check spelling and capitalization.

Start with the export check first — that's where most people run into this issue!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:35:02