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

如何将Sass导出的变量列表转换为Next.js/React中的TypeScript联合类型

问题原因

默认情况下TypeScript无法识别SCSS模块的导出结构,你的项目中通常会存在通用SCSS模块类型声明,内容类似:

declare module '*.module.scss' {
  const content: { [key: string]: string }
  export default content
}

这种声明下SCSS导出对象的键被泛化为字符串类型,自然无法推导得到具体的颜色变量名联合类型。

解决方案

采用typed-scss-modules工具自动生成SCSS文件对应的类型声明,实现SCSS变量变更时类型自动同步,具体操作步骤如下:

  • 安装开发依赖
npm install typed-scss-modules --save-dev
# 或者使用yarn
yarn add typed-scss-modules -D
  • 在package.json中添加类型生成脚本
{
  "scripts": {
    "gen:scss-types": "tsm styles/ --nameFormat none --exportType default",
    "gen:scss-types:watch": "tsm styles/ --nameFormat none --exportType default --watch"
  }
}

参数说明:

  • styles/ 替换为你存放SCSS文件的实际目录
  • --nameFormat none 保持变量名原始格式,不自动转换驼峰/蛇形命名
  • --watch 监听SCSS文件变更,自动更新类型声明,适合开发阶段使用
  • 执行类型生成脚本
    运行npm run gen:scss-types后,工具会自动为每个SCSS模块生成同名的.d.ts类型文件,你的_colors.module.scss对应的声明文件内容如下:
declare const styles: {
  azure: string;
  white: string;
};
export default styles;
  • 开发阶段可同步运行监听脚本,新增/修改SCSS颜色变量时类型会自动更新,无需手动维护,此时你代码中的Color类型会自动被推导为'azure' | 'white',符合预期。

注意:你当前的SCSS文件存在笔误,:export中white对应的值写为$bianca,实际定义的变量名为$white,需要修正否则运行时会取值异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:21:01