P
P
partyzanx2022-01-13 05:47:03
typescript
partyzanx, 2022-01-13 05:47:03

How to allow an empty object in typescript?

Hi

Link to the sandbox

I write this code

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


The output screensWidth object should be like this

{
  min: {
    px1600: min1600px,
    px1280: min1280px,
    // и т.д.
  },
  max: {
    px1600: max1600px,
    px1280: max1280px,
    // и т.д.
  },
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-01-13
@partyzanx

Partial<Record<
    keyof typeof screensWidthEnum,
    `min${screensWidthEnum}px` | undefined
  >>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question