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

TypeScript动态Logo工具函数报错及类型定义问题咨询

TypeScript Logo工具函数问题解决

问题背景

作为TypeScript新手,我需要创建一个工具文件给不同React组件提供应用Logo,当前代码如下:

import full from '../../assets/logo/logo-full.jpg';
import flat from '../../assets/logo/logo-flat.jpg';

const logo = (style: string): full | flat | null => {
    switch(style) {
        case 'full':
            return full;
        
        case 'flat':
            return flat;
    }

    return null;
};

export default logo;

出现错误提示:

Cannot use namespace 'full' as a type. ts(2709)
Cannot use namespace 'flat' as a type. ts(2709)

已添加模块声明:

declare module '*.jpg' {
    const value: any;
    export = value;
}

我有两个问题:

  1. 如何定义该函数的预期返回值类型(可返回full Logo、flat Logo或null)?
  2. 如何限制函数接收的参数仅为'full'或'flat',而非任意string?

解决方案

1. 正确定义返回值类型

报错是因为你把变量full和flat直接当作类型使用了,TypeScript中要获取变量的类型,需要用typeof操作符。

把返回值类型改成typeof full | typeof flat | null,就能准确表示函数可以返回这两个Logo变量对应的类型或者null。

2. 限制参数为指定字符串

直接用字符串字面量类型'full' | 'flat'作为参数的类型,这样TypeScript会强制限制传入的参数只能是这两个字符串,传其他值会直接触发类型报错。如果后续可能扩展更多样式,也可以先定义一个类型别名,方便后续维护。


修改后的完整代码

import full from '../../assets/logo/logo-full.jpg';
import flat from '../../assets/logo/logo-flat.jpg';

// 可选:定义类型别名,方便后续扩展样式
type LogoStyle = 'full' | 'flat';

const logo = (style: LogoStyle): typeof full | typeof flat | null => {
    switch(style) {
        case 'full':
            return full;
        
        case 'flat':
            return flat;
    }

    return null;
};

export default logo;

如果你的模块声明里value的类型可以更具体(比如在React中导入图片实际得到的是URL字符串),可以把模块声明改成这样,让返回值类型更精准:

declare module '*.jpg' {
    const value: string;
    export = value;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:01:08