ウェブサイト検索

javascript - Typescript: boolean型の使用はTSコンパイラで受け入れられません


今は、isLoading を any にしていますが、boolean(本当はそうしたい)にすると、"Loading" 定数にカーソルを合わせたときに以下のエラーが出ます。私の理解では、これは動作するはずです。TypeScript は初心者なので、優しくしてください。どんな助けでもありがたいです。

package.json

"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"typescript": "^4.0.3"

エラーメッセージ

Type '{ ({ isLoading, size, color, }: LoadingProps): false | JSX.Element; defaultProps: Partial<LoadingProps> | undefined; }' is not assignable to type 'FC<LoadingProps>'.
  Type 'false | Element' is not assignable to type 'ReactElement<any, any> | null'.
    Type 'false' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)

index.tsx

import React from 'react';
import ClipLoader from 'react-spinners/ClipLoader';

interface LoadingProps {
  isLoading: any;
  size?: number;
  color?: string;
}

/**
 * Loading icon to let user know a promise is going on
 *
 * @param isLoading Passing true to show spinner, and pass false to remove it
 * @param size react-spinner parameter for size of icon
 * @param color Color of Loading icon
 */

const Loading: React.FC<LoadingProps> = ({
  isLoading,
  size = 35,
  color = '#F6F7FB',
}: LoadingProps) => {
  return isLoading && <ClipLoader size={size} color={color} />;
};

Loading.defaultProps = {
  size: 35,
  color: '#F6F7FB',
};

export default Loading;

回答 #1

`isLoading` が `false` のとき、あなたの return 文は `false` を返しますが、これは `ReactElement` ではありません。

代わりに条件付きレンダリングには常に三項演算子を使用することをお勧めします。例えば:

return isLoading ? <ClipLoader size={size} color={color} /> : null

詳細については、ドキュメントの条件付きレンダリングを参照してください。