技術ブログ

(技術系中心)基本自分用備忘録なので、あくまで参考程度でお願いします。

Type Scriptの型(基本)

Type Scriptの型(基本)

// 型推論の場合は型を定義しなくてもOK
let hasValue = true;
let count = 10;
let float = 3.14;
let negative = -0.12;
let single = 'hello';
let double = "hello";
let back = `hello`;

// 型注釈の場合は型を定義する
let hello: string;
hello = 'hello';

// オブジェクトに型を定義する
const person: {
  name: string
  age: number
} = {
  name: 'jack',
  age: 21
}

// 配列に型を定義する
const fruits: string[] = ['Apple', 'Banana', 'Grape'];

// tuple型を定義する(型定義以外のものがくればエラーになる。より厳密にしたい場合に利用する)
const book: [string, number, boolean] = ['business', 1500, false];

// enum定義もできる
enum CoffeeSize {
  SHORT,
  TALL = 'TALL',
  GRANDE = 1,
  VENTI
}

const coffee = {
  hot: true,
  size: CoffeeSize.TALL
}
coffee.size = CoffeeSize.SHORT;

// anyはなんでも入れる事が出来る(TypeScriptの恩恵を受けれないので基本は利用しないようにする)
let anything: any = true;
anything = 'hello';
anything = ['hello', 33, true];
anything = {};
anything.fjiafjaj = 'faijfi';
let banana = 'banana';
banana = anything;


// unionは複数の型を定義できる
let unionType: number | string = 10;
let unionTypes: (number | string)[] = [21, 'hello']


// unionとliteralを同時に使え
// typeエイリアスを利用して複雑な型を変数のように扱う
type ClothSize = 'small' | 'medium' | 'large';
const apple = 'apple';
let clothSize: ClothSize = 'large';
const cloth: {
  color: string;
  size: ClothSize
} = {
  color: 'white',
  size: 'medium'
}


// 関数に型をつけることも可能
// パラメーターの後(第二引数)に戻り値の型を指定する
function add(num1: number, num2: number): number {
  return num1 + num2
}

// 関数の戻り値にvoidをすると何も返さない(undefined)という意味になる
function sayHello(): void {
  // console.log('Hello!');
}

// console.log(sayHello());
let tmp: undefined;



// 関数型を使えば特定の関数のみ代入できる変数を作成できる
const anotherAdd: (n1: number, n2: number) => number = function (num1, num2) {
  return num1 + num2
};
// アロー関数で書く場合
const doubleNumber: (num: number) => number = num => num * 2;


// callback関数に型をつけることもできる
function doubleAndHandle(num: number, cb: (num: number) => void): void {
  const doubleNum = cb(num * 2);
  // console.log(doubleNum);
}

doubleAndHandle(21, doubleNum => {
  return doubleNum
});

// unknownはanyと一緒でなんでも入れられる
let unknownInput: unknown;
let anyInput: any;
let text: string;
unknownInput = 'hello';
unknownInput = 21;
unknownInput = true;
text = anyInput;
if (typeof unknownInput === 'string') {
  text = unknownInput;
}

function error(message: string) {
  throw new Error(message);
}
console.log(error('This is an error'));