Take a create-react-app application that was created with typescript:
npx create-react-app myapp --template typescript
cd myapp
npm install styled-components@5.0.1
Then add styled-components to a typescript file MyButton.tsx.
import React from 'react';
import styled from 'styled-components'; // <<<<< THIS LINE CAUSES ERROR
const MyButtonStyle = styled.button`
background: #9590eb;
border-radius: 3px;
border: none;
color: white;
`;
/**
* MyButton is a wrapper around a Button component. Props/arguments are:
* onClick(event:object) => void
* style: Pass style onto <button> element
*/
function MyButton(props:any) {
return (
<MyButtonStyle style={props.style} type="button" onClick={props.onClick}>{props.children}</MyButtonStyle>
);
}
export default MyButton;
And I get the error
TypeScript error in .../MyButton.tsx(2,20): Could not find a declaration file for module 'styled-components'. '.../myapp/node_modules/styled-components/dist/styled-components.cjs.js' implicitly has an 'any' type.
To fix this I renamed the file to *.jsx and the problem went away.
I'm just learning typescript so my thought was I needed to install a typescript library to support styled-components
but I haven't figured out how to do that (yet).
Searching
When searching for a solution I came across the following but they didn't answer the question.
Styled-components with TypeScript - This was a file naming problem (*.ts to *.tsx).
Using styled components with Typescript, prop does not exist?
CodePudding user response:
Styled Components library does not ship with types. Instead, you'll need to install it from the Definitely Typed repository.
npm i --save-dev @types/styled-components