TypeScript - השבתת כלל `noImplicitAny` בשורת קוד אחת


פעילתי את "noImplicitAny": true בקובץ tsconfig.json ואני מקבל את השגיאה TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}' בקוד שלי.

אני רוצה להשבית את הכלל הזה עבור שורה אחת וניסיתי עם הקוד למטה, אבל זה לא עבד.

const mockElement = () => ({
  mount: jest.fn(),
  destroy: jest.fn(),
  on: jest.fn(),
  update: jest.fn(),
});

const mockElements = () => {
  const elements = {};
  return {
    create: jest.fn((type) => {
      // getting error from the bellow line
      // tslint:disable-next-line: no-implicit-any
      elements[type] = mockElement();
      // getting error from the bellow line
      // tslint:disable-next-line: no-implicit-any
      return elements[type];
    }),
    getElement: jest.fn((type) => {
      // getting error from the bellow line
      // tslint:disable-next-line: no-implicit-any
      return elements[type] || null;
    }),
  };
};

ישנם הצעות להשבית את הכלל רק עבור שורה אחת? (הגדרה "noImplicitAny": false בקובץ tsconfig.json תעבוד אבל אינה מקובלת כי היא מבטלת את הכלל לחלוטין)

תשובה #1

אתה יכול להשתמש בהוראת @ts-expect-error של ts כדי להתעלם משגיאה לדוגמה:

// @ts-expect-error Parameter 'name' implicitly has an 'any' type.ts(7006)

מידע נוסף: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html#-ts-expect-error-comments

תשובה #2

זו בעיה של ESLint, לא של קומפיילר TypeScript. נסה את זה בקוד המקור שלך

// eslint-disable-next-line @typescript-eslint/no-explicit-any

למרות שזו הגדרה לכל דבר מפורש, אני חושב שאתה יכול לעקוף את זה פשוט על ידי הגדרת זה במפורש רק בשורה אחת שאתה צריך?