Make it to make it

いろいろ作ってアウトプットするブログ

TypeScript学習2(ファンクション周りでの扱い)

ファンクション周りでのannotations/inference使い分け

Type annotations for functions

Code we add to tell TS what type of arguments a function will receive and what type of values it will return.

Type inference for functions

TS tries to figure out what type of value a function will return.

Type inferenceは返却値はファンクションにおいて型付けはしてくれるが、引数に関しては型宣言もしくは初期値の割当が必要

つまり、ファンクションを宣言する際は、このしきたりに従うようにする。

const add = (a: number, b: number) => {
  return a + b;
};

即時関数での記述方法

特に大きな違いはない。

function divide(a: number, b: number) {
  return a / b;
}

const multiply = function(a: number, b: number) {
  return a * b;
};

返却値が存在しないファンクション

voidを指定してあげることで、返却をさせないことができる。

const logger = (message: string): void => {
  console.log(message);
};

Argument destructuring

const forecast = {
  date: new Date(),
  weather: 'sunny'
};

const logWeather = (forecast: { date: Date; weather: string }): void => {
  console.log(forecast);
};

// ES2015
const logWeatherDestructured = ({
  date,
  weather
}: {
  date: Date;
  weather: string;
}): void => {
  console.log(date);
  console.log(weather);
};

Object destructuring

const profile = {
  personName: 'alex',
  age: 20,
  coords: {
    lat: 0,
    lng: 15
  },
  setAge(age: number): void {
    this.age = age;
  }
};

const { age, personName }: { age: number; personName: string } = profile;
const {
  coords: { lat, lng }
}: { coords: { lat: number; lng: number } } = profile;