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
相关产品推荐
相关产品推荐

