Skip to content

Instantly share code, notes, and snippets.

@tonkotsuboy
Last active June 5, 2019 09:15
Show Gist options
  • Select an option

  • Save tonkotsuboy/dab2c4bc2850de9bc5779243cd4e49a9 to your computer and use it in GitHub Desktop.

Select an option

Save tonkotsuboy/dab2c4bc2850de9bc5779243cd4e49a9 to your computer and use it in GitHub Desktop.
ある関数の戻り値しか許容しない型を作る
/** seedに応じた名前を生成する関数です */
const createFirstName = (seed: number) => {
switch (seed) {
case 0:
return "鈴木さん";
case 1:
return "後藤さん";
case 2:
return "マリオ";
default:
return "名無しの小五郎";
}
};
/** createFirstName()で生成される文字列しか許容しない型です */
type MyType = ReturnType<typeof createFirstName>;
// MyType型に好きな文字列を入れてみます
const foo: MyType = "鈴木さん"; // OK
const bar: MyType = "名無しの小五郎"; // OK
const baz: MyType = "エミリー"; // Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment