Last active
June 5, 2019 09:15
-
-
Save tonkotsuboy/dab2c4bc2850de9bc5779243cd4e49a9 to your computer and use it in GitHub Desktop.
ある関数の戻り値しか許容しない型を作る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** 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