javascript - Material UI CSS-in-JS の型付け
私はReact、React Admin、Babel、TypeScript、Webpackを使ってプロジェクトを設定しています。使用しているエディタはVSCodeです。
私は新しいMaterial UIのスタイリングソリューションを使おうとしており、特にStyled ComponentsのAPIを使おうとしています。
TSLint を設定して、変数宣言に typedef を追加することが必須になるようにしています。
次のコードを書くとき:
const StyledButton = styled(Button)({
backgroundColor: 'yellow',
height: 10,
width: 80,
});
TSLint は次のエラーを投げます: expected variable-declaration: 'StyledButton' to have a typedef (typedef)tslint(1)。渡している Button は Material UI から来ているコンポーネントであることに注意してください:
import Button from '@material-ui/core/Button';その後、StyledButton にカーソルを合わせると、次のように表示されます:
要するに、VSCode は StyledButton 変数の型、つまり React.ComponentType を教えてくれているということです。ですので、もし私がコードをこう更新したら:
const StyledButton: React.ComponentType = styled(Button)({
backgroundColor: 'yellow',
height: 10,
width: 80,
});
全くエラーが出ません。素晴らしい!
しかし今、私の問題が始まります:Button を実際の HTML 要素 button に変更するとき:
const StyledButton: React.ComponentType = styled('button')({
backgroundColor: 'yellow',
height: 10,
width: 80,
});
私のエディターは次のエラーを出します:
Type 'ComponentType<never>' is not assignable to type 'ComponentType<{}>'.
Type 'ComponentClass<never, any>' is not assignable to type 'ComponentType<{}>'.
Type 'ComponentClass<never, any>' is not assignable to type 'ComponentClass<{}, any>'.
Types of property 'getDerivedStateFromProps' are incompatible.
Type 'GetDerivedStateFromProps<never, any> | undefined' is not assignable to type 'GetDerivedStateFromProps<{}, any> | undefined'.
Type 'GetDerivedStateFromProps<never, any>' is not assignable to type 'GetDerivedStateFromProps<{}, any>'.
Types of parameters 'nextProps' and 'nextProps' are incompatible.
Type 'Readonly<{}>' is not assignable to type 'never'
typedef を削除して StyledButton に再度カーソルを合わせると、次のように表示されます:
だから VSCode は私に、型が React.ComponentType<never> に変わったと言っています。コードを次のように更新しましょう:
const StyledButton: React.ComponentType<never> = styled('button')({
backgroundColor: 'yellow',
height: 10,
width: 80,
});
そしてエラーはなくなります、いいですね!StyledButtonを使いましょう:
<StyledButton>
I'm a button
</StyledButton>
これにより別のエラーが発生します:
This JSX tag's 'children' prop expects type 'never' which requires multiple children, but only a single child was provided.ts(2745)
私が何か間違っているのでしょうか?それとも?StyledButtonを正しく型指定して、実際にコンポーネントを使用するときにエラーが出ないようにするにはどうすればよいですか?
この問題もGitHubに投稿しましたが、残念ながらクローズされました: https://github.com/mui-org/material-ui/issues/14898
もし追加の情報が必要であれば、教えてください。どうぞよろしくお願いします!

