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

TypeScript将Theme接口的typography对象识别为空类型问题求助

问题排查与解决

1. 核心问题:语法错误导致类型识别异常

你定义theme变量时遗漏了赋值运算符=,这是基础语法错误,导致TypeScript无法正确解析变量声明,进而让编辑器错误地将typography推断为{}类型。

修复后的完整代码:

export type TypographyVariant =
  | 'label-large'
  | 'label-medium'
  | 'label-small';

export interface Theme {
  typography: {
    [key: TypographyVariant]: {
      lineHeight: string;
      fontSize: string;
      letterSpacing?: string;
      fontWeight?: number;
    };
  };
}

// 修复:添加赋值运算符 =
const theme: Theme = {
  typography: {
    'label-large': {
      lineHeight: '20px',
      fontSize: '14px',
      letterSpacing: '0.1px',
      fontWeight: 500,
    },
    'label-medium': {
      lineHeight: '16px',
      fontSize: '12px',
      letterSpacing: '0.5px',
      fontWeight: 500,
    },
    'label-small': {
      lineHeight: '16px',
      fontSize: '11px',
      letterSpacing: '0.5px',
      fontWeight: 500,
    },
  }
};

2. 可选优化:提升类型推断精准度

如果希望编辑器能更清晰地识别typography的具体结构,可以先让TypeScript自动推断原始对象的类型,再将其赋值给Theme类型的变量,配合as const断言还能保留字面量类型:

export type TypographyVariant =
  | 'label-large'
  | 'label-medium'
  | 'label-small';

export interface Theme {
  typography: {
    [key: TypographyVariant]: {
      lineHeight: string;
      fontSize: string;
      letterSpacing?: string;
      fontWeight?: number;
    };
  };
}

const rawTheme = {
  typography: {
    'label-large': {
      lineHeight: '20px',
      fontSize: '14px',
      letterSpacing: '0.1px',
      fontWeight: 500,
    },
    'label-medium': {
      lineHeight: '16px',
      fontSize: '12px',
      letterSpacing: '0.5px',
      fontWeight: 500,
    },
    'label-small': {
      lineHeight: '16px',
      fontSize: '11px',
      letterSpacing: '0.5px',
      fontWeight: 500,
    },
  }
} as const;

const theme: Theme = rawTheme;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:43:30