TypeScript Props with css function
See original GitHub issueThis is arguably a usage question disguised as a request for documentation clarification. I’m struggling with adapting the css
literals based on props, as I can’t find a nice way of “hooking” in the generics.
The following throws a type error as the css
function does not recoqnize the props.primary
interpolation:
import * as styledComponents from "styled-components";
import { ThemedStyledComponentsModule } from "styled-components";
interface Theme {
primaryColor: string;
secondaryColor: string;
}
const { css } = styledComponents as ThemedStyledComponentsModule<Theme>;
export const MyCss = css`
color: ${(props) => props.theme.primaryColor};
background: ${(props) => props.inverted ? props.theme.secondaryColor : props.theme.primaryColor};
`;
css
does have a generic interface with regards to props, however, the following is a syntax error in TypeScript 2.2. I haven’t seen any examples of how (or if) one can use generic tagged template literals in TypeScript – which may be an issue with TypeScript (haven’t seen one reported):
interface Props {
inverted: boolean;
}
export const MyCss = css<Props>`
color: ${(props) => props.theme.primaryColor};
background: ${(props) => props.inverted ? props.theme.secondaryColor : props.theme.primaryColor};
`;
A working solution is to explicitly give the type of props in the interpolated functions where it matters, which isn’t so bad if you use an alias (badly named here, however).
type P = ThemedStyledProps<Props, Theme>;
export const MyCss = css`
color: ${(props) => props.theme.primaryColor};
background: ${(props: P) => props.inverted ? props.theme.secondaryColor : props.theme.primaryColor};
`;
Could this be clarified in the docs? I can’t see any examples of CSS adapting based on props – only on theme.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:5
- Comments:6 (4 by maintainers)
Top GitHub Comments
@Igorbek I can write some docs tomorrow, I think that’s better to document this way:
What do you think?
The code is very verbose compared to css/less variables. I’m not yet convinced of using styled components 😅