Jest/TypeScript报错fontSize属性不存在,但该属性实际存在
TypeScript静态类型检查报错:Property 'fontSize' does not exist on type 'object'
场景重现
定义的Typography对象
export const Typography: ITypographyBase = { fontFamily: '"IBM Plex Sans", "Helvetica Neue", sans-serif', fontSize: BASE_FONT_SIZE, name: 'Typography', toJS: function () { return Object.entries(this).reduce( (acc, [key, value]) => { if (!isValidCSSProperty(kebabCase(key))) return acc; const transformedValue = this.transformValue(key, value, this.fontSize); return { ...acc, [key]: transformedValue }; }, {}, ); }, transformValue: function (property, input, fontSize) { switch (property) { case 'fontSize': return toNumberWithUnit(input / BASE_FONT_SIZE, 'rem'); case 'letterSpacing': return toNumberWithUnit(input / fontSize, 'em'); case 'lineHeight': return toNumberWithUnit(input / fontSize, 'em'); default: return input; } }, };
测试代码
describe('computed values', () => { test('fontSize', () => { const styles = { ...Typography, fontSize: 24, }; const type = styles.toJS(); console.log('type', Object.keys(type)); expect(type.fontSize).toEqual('1.5rem'); }); });
报错信息
src/lib/tokens/typography.test.ts:17:17 - error TS2339: Property 'fontSize' does not exist on type 'object'.
运行时输出
type ['fontFamily', 'fontSize']
问题原因
TypeScript是静态类型检查器,编译阶段仅做代码分析不执行代码。toJS()方法中reduce的初始值为{},TypeScript默认推断该方法返回类型为object(空对象类型),无法识别运行时会动态添加fontSize、fontFamily等属性,因此抛出属性不存在的错误。
解决方法
1. 给toJS()指定明确的返回类型
先定义目标CSS属性接口,再修改ITypographyBase接口明确返回值类型:
// 定义Typography转换后的CSS属性类型 interface TypographyCSS { fontFamily: string; fontSize: string; // 按需添加其他可能的CSS属性 } interface ITypographyBase { fontFamily: string; fontSize: number; name: string; // 指定toJS返回TypographyCSS类型 toJS(): TypographyCSS; transformValue(property: string, input: any, fontSize: number): any; }
TypeScript会提前识别toJS()返回对象包含fontSize属性,不再报错。
2. 使用类型断言快速解决
若不想修改接口,可直接对返回值做类型断言:
const type = styles.toJS() as { fontSize: string; fontFamily: string };
注意:需确保断言类型与实际返回值完全匹配,否则可能隐藏运行时问题。
3. 让TypeScript自动推断返回类型
修改reduce累加器类型,让TypeScript自动推断最终返回结构:
toJS: function () { return Object.entries(this).reduce( // 给累加器指定Partial<TypographyCSS>类型 (acc: Partial<TypographyCSS>, [key, value]) => { if (!isValidCSSProperty(kebabCase(key))) return acc; const transformedValue = this.transformValue(key, value, this.fontSize); return { ...acc, [key]: transformedValue }; }, {}, ); },
Partial<TypographyCSS>表示包含TypographyCSS部分属性的对象,TypeScript会根据累加过程推断最终完整类型。
内容的提问来源于stack exchange,提问作者Brandon Durham
相关产品推荐
相关产品推荐

