如何使用打字稿解决 React 上的"Type '{ body: string; text: string; }' is not assignable to type 'DefaultTheme



我是编程新手,现在我正在使用React与Typescript和样式组件进行我的第一个项目。我试图添加一个黑暗模式组件为我的网站,但2天我遇到了一个问题,我无法克服。

这是我的App.tsx:

const App = () => {
const [theme, setTheme] = useState('light');
const themeToggler = () => {
theme === 'light' ? setTheme('dark') : setTheme('light')
}
return (
<ThemeProvider theme = {theme === 'light' ? lightTheme : darkTheme}>
<>
<Navbar />
<button onClick={themeToggler}>Switch Theme </button>
<GlobalStyle text={""} body={""} background={""} toggleBorder={""} />
{<Routes location={location} key={location.pathname}>
<Route path='/' element={<MainPage />} />
<Route path='/about' element={<About />} />
<Route path='/portfolio' element={<Portfolio />} />
<Route path='/contact' element={<Contact />} />
</Routes> }
</>
</ThemeProvider>
)
}

我styled.d.tsx

declare module 'styled-components' {
export interface DefaultTheme {
background: string
toggleBorder: string
text: string
body: string
}
export interface ColorsInterface {
primary: string
secondary: string
}
}

这是我无法解决的错误。

Type '{ body: string; text: string; }' is not assignable to type 'DefaultTheme | ((theme: DefaultTheme) => DefaultTheme)'.
Type '{ body: string; text: string; }' is missing the following properties from type 'DefaultTheme': background, toggleBorderts(2322)
index.d.ts(350, 5): The expected type comes from property 'theme' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemeProviderProps

我正在尝试用黑暗主题和光明主题做一个黑暗模式的主题改变器

我相信你得到了这个错误,因为你的接口DefaultTheme定义了属性background: string, toggleBorder: string, text: string, body: string和这个对象Type '{ body: string; text: string; }'没有所有的属性。

最新更新