LoginSignup
20
10

More than 3 years have passed since last update.

【TypeScript】Utility TypesのParametersを深く理解する

Last updated at Posted at 2021-03-07

この記事は何?

この記事は、Utility Typesの一つであるParametersについて深く理解する記事です。
Utility Typesってそもそも何?という型(方)は以下の記事を御覧ください🙇🏻
👉 TypeScriptのUtility Typesを理解して活用する

そもそも、TypeScriptって何?って型は以下を御覧ください
👉 JavaScriptを知っている方がTypeScriptをなんとなく理解するための記事① ~はじめに~

Parameters<Type, Keys>とは

TypeScript公式には以下のように書かれています。

Constructs a tuple type from the types used in the parameters of a function type Type.
関数型Typeのパラメーターで使用される型からタプル型を構築します。
https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

ちょっとわかりづらいですね😅

因数分解すると以下のような意味になります。
- 関数型Typeのパラメーターで使用される型から → 関数の引数の型から
- タプル型を構築します。 → タプル型を構築する

つまり、Parameterは、関数を使ってタプル型を生成するものです。

実際にコードの場合、以下のように表すことが出来ます。

type hogehoge = Parameters<関数型>
// type nonTuple = []
type nonTuple = Parameters<() => string>; // 引数がないので空タプル

// type stringTuple = [value: string]
type stringTuple = Parameters<(value: string) => string>; // 引数がstringのタプル

const callAnimal = (animalName: string, owner: string): void => {
  console.log(`${animalName}${owner}の近くにおいで!`);
}

// type animalTuple = [animalName: string, owner: string]
type animalTuple = Parameters<typeof callAnimal>; // 引数が2つなので、2つ要素のあるタプル

このParameters<>はどのようなシーンで利用するのでしょうか?

これは個人的に考えた用途なのですが、サードパーティーの関数を利用する時に使えるのではないかと考えています。

例えば、以下のような関数を含むパッケージをインストールするとします。

plusOneMessage.ts
export const plusOne = (num: number, greeting: string): string => {
  return `${greeting}${num}をプラス1すると${num + 1}が得られます。`;
};

そして、この関数を利用してみます。

// plusOne関数をimport
import { plusOne } from "./plusOneMessage";

// 予めplusOne関数の引数の型を`Paramaters`で作る
type plusOneType = Parameters<typeof plusOne>; // type plusOneType = [num: number, greeting: string]

// plusOne関数にわたす予定の定数の型を指定する。
const inputForm: plusOneType = [100, "こんにちは"]; // const inputForm: [num: number, greeting: string]

// plusOneを使う
console.log(plusOne(...inputForm)); // こんにちは、100をプラス1すると101が得られます。

このように、誤った型の引数を関数に渡さないよう、予めParamatersで関数の型を作っておいて、引数に関数の型を指定します。
この関数から作った型を使えば、誤った型を持つ引数を渡すことが防げます。
また、わざわざplusOneの関数の型をinterfeceで作る必要もありません。

また、React&TypeScriptであれば、以下のように使っても良いかもしれません。

import { plusOne } from "./plusOneMessage";

type Props = Parameters<typeof plusOne>;

const hogehogeComponent: React.FC<Props> = (props) => {
 ...
}

以上のように、利用できるかと思います。
他にも、良い利用方法があれば是非コメント欄で教えて下さい!

おわりに

今回は、Utility TypesのParametersについて紹介しました。
是非、ご活用ください!

参考

20
10
1

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
20
10