0
0

TypeScript初学者の振り返り

Posted at

はじめに

TypeScriptを勉強していく中で、印象的だったものを書き出していく。

null

型宣言をしたプロパティに対してnullの代入を行うとエラーになる。
後述するユニオンをしようするとnullも許容することができる。
tsconfig.jsonのstrictNullChecksを無効にすると、すべての型にnullやundefinedが許可される。

let test1: string = "aaa";
test1 = null;

let test2: number = 1;
test2 = null;

let test3: null = null;

let test4: string | null = "bbb";
test4 = null;

ユニオン型

関数の引数やオブジェクトのプロパティに対して型を指定する際、複数の型を指定することができる記法。

const test = (age: number | string) => console.log(`im ${age}  years old`);

test(20);    // im 20  years old
test("20");  // im 20  years old

test(false); // 型エラー

リテラルを指定することで、特定の値のみに制限することもできる。

const test = (value: "world" | "country" | 10) => console.log(`hello ${value}`);

test("world");   // hello world
test("country"); // hello country
test(10);        // hello 10

test("people");  // 型エラー

オプショナルパラメータ

関数の引数やオブジェクトのプロパティに対して指定することができ、値を設定しなくても良いパラメータを作り出すことができる。
値の設定有無が自由なのはメリットに思える反面、外側から見るとプロパティの有無が担保されない側面もある。

未設定のオプショナルプロパティはundefinedになる。

const test = (value?: string) => `hello ${value}`;

console.log(test("world")); //hello world
console.log(test());        //hello undefined
interface Test {
  name: string;
  age?: number;
}

const test1: Test = { name: "TARO" };
const test2: Test = { name: "ZIRO", age: 20 };

console.log(test1); // { name: 'TARO' }
console.log(test2); // { name: 'ZIRO', age: 20 }

コンストラクタ引数でのインスタンス変数宣言

通常、インスタンス変数を宣言する際はコンストラクタの外側に記述する必要がある。

class Test {
  public name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

const test = new Test("Alice", 30);

コンストラクタ引数内でアクセス修飾子を付与することで、インスタンス変数の宣言と設定を省くことができる。

class Test {
  constructor(public name: string, private age: number, isMan: boolean) {}
}

const test = new Test("aaa", 20, true);
console.log(test.name);  // aaa
console.log(test.isMan); // インスタンス変数は存在しないのでエラー
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