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

TypeScript类型与常量同名报错:FeatureFlags已声明,能否实现该写法?

TypeScript中能否声明与自定义类型同名的常量对象?

想声明一个与自定义类型FeatureFlags同名的常量对象,但报错FeatureFlags is already declared,请问是否可以实现这种同名写法,还是必须修改类型声明的名称?

相关代码:

export type FeatureFlags = {
  [key: string]: {
    name: string;
    defaultValue: boolean;
  };
};

export const FeatureFlags: FeatureFlags = {
  SOME_FLAG: {
    name: 'test-flag',
    defaultValue: false,
  },
};

在TypeScript里,类型(比如type/interface定义的实体)和值(比如常量、变量、函数这类会存在于运行时的实体)共享同一个模块/全局命名空间,因此不能同时声明同名的类型和值,必须修改其中一方的名称。

推荐两种修改方案:

  • 方案1:修改类型名称,通常会给类型加上Type后缀来区分:
export type FeatureFlagsType = {
  [key: string]: {
    name: string;
    defaultValue: boolean;
  };
};

export const FeatureFlags: FeatureFlagsType = {
  SOME_FLAG: {
    name: 'test-flag',
    defaultValue: false,
  },
};
  • 方案2:修改常量名称,遵循JS/TS变量命名惯例用小驼峰:
export type FeatureFlags = {
  [key: string]: {
    name: string;
    defaultValue: boolean;
  };
};

export const featureFlags: FeatureFlags = {
  SOME_FLAG: {
    name: 'test-flag',
    defaultValue: false,
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:18:18