-
Notifications
You must be signed in to change notification settings - Fork 108
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #902 from yytypescript/feature/899
Feature/899
- Loading branch information
Showing
3 changed files
with
48 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
--- | ||
description: 関数の戻り値の型を取得する | ||
title: "ReturnType<T>" | ||
--- | ||
|
||
`ReturnType<T>`は、関数型`T`の戻り値を取得するユーティリティ型です。 | ||
|
||
## ReturnType<T>の型引数 | ||
|
||
### T | ||
|
||
型引数`T`には、関数の型を渡します。関数でない型を渡すと`never`型になります。 | ||
|
||
## NonNullableの使用例 | ||
|
||
```ts twoslash | ||
// @errors: 2344 | ||
type ReturnType1 = ReturnType<() => string>; | ||
// ^? | ||
type ReturnType2 = ReturnType<(arg: string) => string | number>; | ||
// ^? | ||
type ReturnType3 = ReturnType<() => never>; | ||
// ^? | ||
``` | ||
|
||
多くは`typeof`と併用して実際の関数の戻り値を取得します。 | ||
|
||
```ts twoslash | ||
const isEven = (num: number) => { | ||
return num / 2 === 0; | ||
}; | ||
|
||
type isEvenRetType = ReturnType<typeof isEven>; | ||
// ^? | ||
``` | ||
|
||
`ReturnType<T>`は内部的には`infer`を使って実装されています。 | ||
|
||
```ts twoslash | ||
// @noErrors | ||
type ReturnType<T extends (...args: any) => any> = T extends ( | ||
...args: any | ||
) => infer R | ||
? R | ||
: any; | ||
``` |
This file contains 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