partyzanx
@partyzanx

Как в typescript допустить пустой объект?

Привет

Ссылка на песочницу

пишу такой код

enum screensWidthEnum {
  px1600 = "1600",
  px1280 = "1280",
  px1024 = "1024",
  px960 = "960",
  px800 = "800",
  px640 = "640",
  px480 = "480",
  px400 = "400",
  px360 = "360",
  px320 = "320",
}


interface TScreensWidth {
  min: Record<
    keyof typeof screensWidthEnum,
    `min${screensWidthEnum}px` | undefined
  >;
  max: Record<
    keyof typeof screensWidthEnum,
    `max${screensWidthEnum}px` | undefined
  >;
}

export const screensWidth: TScreensWidth = {
  min: {}, // Type '{}' is missing the following properties from type 'Record<"px1600" | "px1280" | "px1024" | "px960" | "px800" |  "px640" | "px480" | "px400" | "px360" | "px320", "min1600px" | "min1280px" | "min1024px" | "min960px" | "min800px" | "min640px" | ... 4 more ... | undefined>': px1600, px1280, px1024, px960, and 6 more.ts(2740)

  max: {}, // same error
};

Object.keys(screensWidthEnum).forEach((width) => {
// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<"px1600" | "px1280" | "px1024" | "px960" | "px800" | "px640" | "px480" | "px400" | "px360" | "px320", "min1600px" | "min1280px" | "min1024px" | "min960px" | "min800px" | "min640px" | ... 4 more ... | undefined>'.   No index signature with a parameter of type 'string' was found on type 'Record<"px1600" | "px1280" | "px1024" | "px960" | "px800" | "px640" | "px480" | "px400" | "px360" | "px320", "min1600px" | "min1280px" | "min1024px" | "min960px" | "min800px" | "min640px" | ... 4 more ... | undefined>'.ts(7053)
  screensWidth.min[width] = `min${width}px`;

  screensWidth.max[width] = `max${width}px`; // same error
});

screensWidth.min.px1280


На выходе объект screensWidth должен быть таким

{
  min: {
    px1600: min1600px,
    px1280: min1280px,
    // и т.д.
  },
  max: {
    px1600: max1600px,
    px1280: max1280px,
    // и т.д.
  },
};
  • Вопрос задан
  • 952 просмотра
Решения вопроса 1
Alexandroppolus
@Alexandroppolus
кодир
Partial<Record<
    keyof typeof screensWidthEnum,
    `min${screensWidthEnum}px` | undefined
  >>
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы