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

TypeScript用常量定义字面量类型时出现找不到命名空间错误

问题:从常量定义TypeScript类型时出现命名空间未找到和导入未使用警告

问题场景

想要通过常量文件统一定义类型,确保其他代码都引用常量值,但遇到两个TypeScript警告:

  • Cannot find namespace 'DIRECTION_TYPES'
  • All imports in import declaration are unused

常量文件(constants.ts)

export const INPUT_TYPES = {
  forward: 'F',
  left: 'L',
  right: 'R',
} as const;

export const DIRECTION_TYPES = {
  north: 'N',
  south: 'S',
  east: 'E',
  west: 'W',
} as const;

类型文件(types/mower.d.ts)

import { INPUT_TYPES, DIRECTION_TYPES } from '../constants';

export type MowerInput =
    INPUT_TYPES.forward |
    INPUT_TYPES.left |
    INPUT_TYPES.right;

export type Direction =
    DIRECTION_TYPES.north |
    DIRECTION_TYPES.sotuh |
    DIRECTION_TYPES.east |
    DIRECTION_TYPES.west;

export type Position = {
    x: number;
    y: number;
}

export type Mower = {
    direction: Direction;
    position: Position;
};

问题原因

  1. 拼写错误:类型定义里的DIRECTION_TYPES.sotuh是笔误,正确拼写应为south,这直接导致TS找不到对应属性。
  2. 值与类型混淆:导入的INPUT_TYPES和DIRECTION_TYPES是运行时值,不是类型。在TypeScript的类型上下文里,直接引用值的属性会被误认为是命名空间引用;同时TS会判定这些导入的值没有被实际使用(因为只在类型层面引用),所以抛出“导入未使用”警告。

解决方案

第一步:修正拼写错误

把DIRECTION_TYPES.sotuh改为DIRECTION_TYPES.south,解决属性找不到的基础问题。

第二步:正确关联常量与类型

根据是否需要在代码中使用常量值,有两种处理方式:

方式一:仅用于类型定义(推荐)

使用TypeScript 3.8+支持的类型导入,明确告诉TS这些导入仅用于类型层面,同时用typeof获取常量的类型,再自动提取所有值类型:

import type { INPUT_TYPES, DIRECTION_TYPES } from '../constants';

// 自动提取常量的所有值类型,无需逐个枚举
export type MowerInput = typeof INPUT_TYPES[keyof typeof INPUT_TYPES];
export type Direction = typeof DIRECTION_TYPES[keyof typeof DIRECTION_TYPES];

export type Position = {
    x: number;
    y: number;
}

export type Mower = {
    direction: Direction;
    position: Position;
};
  • typeof INPUT_TYPES获取常量对象的类型
  • keyof typeof INPUT_TYPES获取常量对象的所有键名
  • 最终typeof INPUT_TYPES[keyof typeof INPUT_TYPES]会得到所有键对应的值类型集合(比如'F' | 'L' | 'R')

方式二:同时使用常量值和类型

如果需要在代码逻辑中直接使用INPUT_TYPES等常量值,保留普通导入,先通过typeof将值转为类型,再引用:

import { INPUT_TYPES, DIRECTION_TYPES } from '../constants';

// 将常量值转为类型
type InputTypes = typeof INPUT_TYPES;
type DirectionTypes = typeof DIRECTION_TYPES;

// 手动指定需要的属性类型,或用keyof自动枚举
export type MowerInput = InputTypes['forward' | 'left' | 'right'];
export type Direction = DirectionTypes['north' | 'south' | 'east' | 'west'];

export type Position = {
    x: number;
    y: number;
}

export type Mower = {
    direction: Direction;
    position: Position;
};

这种方式既可以在逻辑代码中使用INPUT_TYPES.forward这样的常量值,也能在类型层面正确引用,同时避免“导入未使用”的警告。


内容的提问来源于stack exchange,提问作者Guillermo Bascuñana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:05:34