Skip to content

Commit

Permalink
Merge pull request #902 from yytypescript/feature/899
Browse files Browse the repository at this point in the history
Feature/899
  • Loading branch information
jamashita authored Oct 4, 2024
2 parents c4ca613 + 415a287 commit b538c3b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1528,7 +1528,7 @@ type T3 = Extract<T1, T2>;

#### NonNullable

- `NonNullable`は、nullまたはundefinedを含む型からいずれも除外するユーティリティ型。
- [`NonNullable`](reference/type-reuse/utility-types/nonnullable.md)は、nullまたはundefinedを含む型からいずれも除外するユーティリティ型。

```typescript twoslash
type T1 = string | null | undefined;
Expand Down
46 changes: 46 additions & 0 deletions docs/reference/type-reuse/utility-types/return-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
description: 関数の戻り値の型を取得する
title: "ReturnType<T>"
---

`ReturnType<T>`は、関数型`T`の戻り値を取得するユーティリティ型です。

## ReturnType&lt;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;
```
1 change: 1 addition & 0 deletions sidebars.js
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ module.exports = {
"reference/type-reuse/utility-types/extract",
"reference/type-reuse/utility-types/no-infer",
"reference/type-reuse/utility-types/nonnullable",
"reference/type-reuse/utility-types/return-type",
],
},
"reference/type-reuse/mapped-types",
Expand Down

0 comments on commit b538c3b

Please sign in to comment.