LoginSignup
0
0

【Typescript】nullとundefined,anyとunknown

Posted at

はじめに

学習の備忘録として残します。
以下について書いています。
・null
・undefined
・any
・unknown

null と undefined

null

値が欠如していることを表す
イメージはトイレットペーパーのホルダー。

undefined

初期化されておらず値が割り当てられていないことを表す。
できる限りundefinedを使用する

type Hoge = {
  optional?: string; //「?」をつけているので、string | undefinedとして扱われる
  notOptional: string | undefined;
};

const hoge1: Hoge = {
  //「?」をつけていたoptionalプロパティは省略可能
  notOptional: "fuga",
};

const hoge2: Hoge = {
  optional: "fuga",
  notOptional: undefined, //「?」をつけていないので、存在しない場合undefinedを明示する必要がある
};

any と unknown

any

どんな型でも許容する → 全く安全ではない。
イメージはメタモン → どんなポケモンにも変化できる

const anySample = () => {
  let name: any = "daichi";
  console.log("any sample 1", typeof name, name);
  //any sample 1 string daichi

  name = 23;
  console.log("any sample 2", typeof name, name);
  //any sample 2 number 23
};

unknown

どんな型になるのか不明。
unknownは代入した値によって型が変化する。
イメージはイーブイ → 特定の進化ができる

const unknownSample = () => {
  const maybeNumber: unknown = 10;
  console.log("unknown sample 1", typeof maybeNumber, maybeNumber);
  //unknown sample 1 number 10

  const isFoo = maybeNumber === "foo";
  console.log("unknown sample 2", typeof isFoo, isFoo);
  //unknown sample 2 boolean false

  if (typeof maybeNumber === "number") {
    const sum = maybeNumber + 10;
    console.log("unknown sample 3", typeof sum, sum);
    //unknown sample 3 number 20
  }
};

おわりに

参考の記事が非常によかったです。
何度も確認しようと思います。

参考

https://qiita.com/marumaru0113/items/d40ab552d7d699e68a6e
https://typescriptbook.jp/reference/statements/never#never%E3%81%AE%E7%89%B9%E6%80%A7

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