I'm migrating my React
app that I've built with styled-components
to Typescript.
In my UI components, I usually create an empty object LS = {};
and add the styled
components as properties of that object.
Note: LS
stands for "Local styles", and I think it's a nice way to visually separate components that are declared inside the file, from components that are being imported from another module.
For example:
MyComponent.tsx
import React from "react";
import styled from "styled-components";
import PostCard from "@components/PostCard";
const LS = {};
LS.Title_DIV = styled.div`
// SOME CSS RULES
`;
const MyComponent = (props) => {
return(
<PostCard>
<LS.Title_DIV>
This is the title
</LS.Title_DIV>
</PostCard>
);
};
export default MyComponent;
While this worked fine in my JS environment, I'm getting errors in my TS environment.
I've tried to include this:
import styled, { StyledComponent } from "styled-components";
interface LS_Object {
[key: string]: StyledComponent
};
const LS: LS_Object = {}
Then the Title_DIV
error goes away, but I get this new error:
This is my tsconfig.json at this point:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"esModuleInterop": true,
// "isolatedModules": true,
"jsx": "react",
"module": "CommonJS",
// "module": "ES6",
// "moduleResolution": "Node",
// "noEmit": true,
"strictNullChecks": true,
"target": "ES5",
"paths": {
"@components/*": ["./src/components/*"],
}
},
"include": [
"src/**/*"
],
// "exclude": [
// "node_modules",
// "dist",
// "public"
// ]
}
QUESTION
Is there a way that I can make this pattern work?
i think the best approach here would be something like this:
const LS = {
Title_DIV: styled.div`
//CSS
`,
};
const MyComponent = (props) => {
return(
<PostCard>
<LS.Title_DIV>
This is the title
</LS.Title_DIV>
</PostCard>
);
};
If you want to explicit define the type and use interface, you can get it hovering the tag, like:
And then, use it like this:
import styled, { StyledComponentBase } from "styled-components";
interface LS_Object {
Title_DIV: StyledComponentBase<"div", any, {}, never>;
}
const LS: LS_Object = {
Title_DIV: styled.div`
// SOME CSS RULES
`,
};
const MyComponent = (props) => {
return(
<PostCard>
<LS.Title_DIV>
This is the title
</LS.Title_DIV>
</PostCard>
);
};
Hope it helps you, cheers!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.