Jest/Typescript为未丢失的丢失属性引发错误

wtlkbnrh  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(161)

我有这个对象literal:

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;
    }
  },
};

字符串
这个简单的测试使用Jest和ts-jest

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'.


.但是console.log('type', Object.keys(type));行回显以下响应:

type ['fontFamily', 'fontSize']


怎么回事?

4uqofj5v

4uqofj5v1#

刚刚意识到,如果我执行以下任一操作,测试将通过:
1.将类型Assert添加到styles.toJS()的结果中:

const type = styles.toJS() as ITypographyBase;

字符串
1.将// @ts-nocheck添加到文件的顶部。

相关问题