使用TypeScript+React时,导入枚举为何出现未定义属性报错?
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.,
utilinstead ofutils) - Is the relative path accurate? (e.g., maybe it should be
../../common/utilsif your current file is nested one level deeper) - If you're using a less common file extension (like
.tsxinstead 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

