LoginSignup
3
1

More than 1 year has passed since last update.

[React×TypeScript]型 'xxx | undefined' を型 'xxx' に割り当てることはできません

Last updated at Posted at 2022-11-09

React.js×TypeScriptでの実装中に、型 'xxx | undefined' を型 'xxx' に割り当てることはできません。というエラーにぶち当たった。

これは、undefinedを制限し、安全な型を子コンポーネントに渡すことで解決できる。

起きたエラー

例えば以下のような構成でParent.tsxからChild.tsxにPropsで値を渡す場合を考える。

.
├── Parent.tsx
└── Child.tsx
Parent.tsx
import { useEffect, useState } from 'react';
import Child from './Child';

export type User = {
  name: string;
  age: number;
  birthplace: string;
};

const Parent = () => {
  const [inputUser, setInputUser] = useState<User>();
  return (
    <>
      <div>{/* 入力フォーム(ここでsetInputUserするイメージ) */}</div>
      <Child user={inputUser}></Child>
    </>
  );
};

export default Parent;

Child.tsx
import { User } from './Parent';

type Props = {
  user: User;
};

const Child = ({ user }: Props) => {
  return (
    <>
      <div>{user.name} </div>
      <div>{user.age} </div>
      <div>{user.birthplace} </div>
    </>
  );
};

export default Child;

Parent.tsxで定義した型UserをChild.tsxでもimportし、Propsの型として利用しているが、Parent.tsxのuseStateで管理しているしているinputUserはundefindになりうるため、Parent.tsxからChild.tsxへデータを渡そうとしている箇所で型エラーとなる。

  • VSCodeでのエラーメッセージ

image.png

エラーメッセージには型 'User | undefined' を型 'User' に割り当てることはできません。と表示される。

解決策

論理 && 演算子を利用することで、<Child>には、undefinedではないデータinputUserを渡すことができる。

Parent.tsx
return (
    <>
      <div>{/* インプットフォーム */}</div>
      {inputUser && <Child user={inputUser}></Child>}
    </>
  );
  • VSCodeでも見てもundefinedのユニオンが消えている

image.png

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1