0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsのComposition APIで学ぶ、TypeScriptのジェネリクスについて

Posted at

ジェネリクスとは

「抽象化されたデータ型」を表現する機能です。
同じようなコードを別の型だからという理由で、複数書いているときなどに使います。

では、実際にサンプルコードを書いていきます。

ジェネリクスの簡単な具体例

textnumberも引数で受けた値をreturnで返しているだけですが、型が違うためコードを分けています。

sample.vue
<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api';
export default defineComponent({
  setup() {
    const text = (val: string): string => {
      return val;
    };
    const number = (val: number): number => {
      return val;
    };
  },
});
</script>

これがその他の型でもあるとしたらすごく冗長ですよね。

image.png

ということで、ジェネリクスを使いましょう!

sample.vue
<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api';
export default defineComponent({
  setup() {
    const option = <T>(val: T): T => {
      return val;
    };

    const text = option<string>('hello');
    const number = option<number>(100);
    const boolean = option<boolean>(false);
  },
});
</script>

上記では抽象的な型引数<T>をメソッドに与え、実際に利用されるまで型が確定しないメソッドを作成しています。

これで1つのコードを書くだけで使い回すことができます!

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?