🐾

TypeScriptのParameters<T>を知ろう

に公開

概要

別記事を書くにあたりParameters<T>を理解しようの会

Parameters<T>とは

ユーティリティ型の1つ。

関数の型Tを渡すとそのパラメータのタプルの型で返すもの。
参考: https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

引数がない場合
type HogeFunc = () => string;
const hogeFunc: HogeFunc = () => {
  return "ほげ";
};

type Hoge = Parameters<HogeFunc>; // []
引数が1つの場合
type HogeFunc = (name: string) => string;
const hogeFunc: HogeFunc = (name: string) => {
  return `${name}です`;
};

type Hoge = Parameters<HogeFunc>; // [string]
引数が複数の場合
type HogeFunc = (name: string, age: number) => string;
const hogeFunc: HogeFunc = (name: string, age: number) => {
  return `${name}です。${age}歳です。`;
};

type Hoge = Parameters<HogeFunc>; // [string, number]

引数にreadonlyがある場合

readonlyもそのまま引き継がれる。

type HogeFunc = (name: readonly string[], age: number) => string;
const hogeFunc: HogeFunc = (name, age) => {
  return `${name.join("と")}です。${age}歳です。`;
};

type Hoge = Parameters<HogeFunc>; // [readonly string[], number]

const hoge: Hoge = [["ほげ", "ふが"], 20];
hoge[0].push("ぴよ"); // 🚫readonlyなのでエラーになっている

引数にオプショナルがある場合

オプショナルもそのまま引き継がれる。

type HogeFunc = (name: string, age: number, hasMessage?: boolean) => string;
const hogeFunc: HogeFunc = (name, age, hasMessage) => {
  const text = hasMessage ? "こんにちは" : "";
  return `${name}です。${age}歳です。${text}`;
};

type Hoge = Parameters<HogeFunc>; // [string, number, boolean?]

const hoge: Hoge = ["ほげ", 20, true]; // ✅booleanなのでOK
const fuga: Hoge = ["ほげ", 20]; // ✅オプショナルなので省略してもOK

Discussion