Issue
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
createBreakpoints(screenSizes)
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?
Solution
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