How to write better TypeScript type to solve two errors


Sorry guys if the title is not clear not sure in this particular case how i should name it.

So i have my object

export const screenSizes: typeScreenSizes = {
  // xxs: '320px', // iPhone 5/SE
  // xs: '375px', // iPhone X
  sm: '576px', // Mobile
  md: '768px', // iPad
  lg: '992px', // Laptop
  xl: '1200px', // Desktop

And i’m using this in two different places different way.

1st place

export const mq = (n: string) => `@media (min-width: ${screenSizes[n]})`

2nd place


In both of those instances I’m getting TS error, so to fix’ish them i wrote my type like so

export type typeScreenSizes = {
  [T: string]: string
  sm: string
  md: string
  lg: string
  xl: string

But I’m sure this is not right, but I’m not sure how can i write this better, i think Generic i need to use?

1st Error:
enter image description here

2nd Error:
enter image description here


screenSizes is an object of type typeScreenSizes with members sm, md, lg and xl. To index this object you are allowed to use either one of these four values. But string is too generic to index it, because it could also be abc for example which is not a member of the type typeScreenSizes.

To fix this problem you have to change the type of the parameter in mq to only allow one of the four values above:

export const mq = (n: keyof typeScreenSizes) => `@media (min-width: ${screenSizes[n]})`

Answered By – Peter Lehnhardt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published