0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React + TypeScript – 複数の型定義 UnionType を UseState / UseEffectで使う

Posted at

コード例

以下でコメントアウトで示した行のように未定義の文字を扱おうとするとエラーを起こしてくれる

import React, { useState, useEffect } from 'react';

export const UnionType = () => {
  type ValueTypes = 'A' | 'B';

  const [value, setValue] = useState<ValueTypes>();

  const clickA = () => {
    setValue("A")
  }

  const clickB = () => {
    setValue("B")
  }

  // Error
  // const clickC = () => {
  //   setValue("C")
  // }

  useEffect(() => {
    switch (value) {
      case "A":
        console.log("is A")
        break
      case "B":
        console.log("is B")
        break
      // Error
      // case "C":
      //   console.log("is C")

    };
  });


  return (
    <div>
      <button onClick={clickA}>ClickA</button>
      <button onClick={clickB}>ClickB</button>
    </div>
  );

};

export default UnionType;

環境

  • react@18.2.0
  • next@13.1.1

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?