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 1 year has passed since last update.

Nuxt.js + TypeScriptにて、useAsync + $axiosで受け取ったresponseの型判定を行う方法

Posted at

axiosのresponseは型がanyになってしまう...
その問題を解決するための方法です!

<template>
    <div>
        <h1>記事一覧</h1>
        <ul>
            <li v-for="post in posts" :key="post.id">
                {{ post.title }}
            </li>
        </ul>
    </div>
</template>

<script lang="ts">
import { defineComponent, useAsync, useContext } from '@nuxtjs/composition-api';

// 対象の型
type Post = {
    userId: number;
    id: number;
    title: string;
    body: string;
};

// ここで型ガード!!
const implementsPost = (arg: any): arg is Post => {
    return arg &&
        typeof arg.userId === 'number' &&
        typeof arg.id === 'number' &&
        typeof arg.title === 'string' &&
        typeof arg.body === 'string';
}

// ここでは配列の型ガード!!
const implementsPosts = (args: any[]): args is Post[] => {
    // 配列1つ1つに型がマッチしているか判定
    return args.every((arg: Post): boolean =>
        implementsPost(arg)    
    );
}

export default defineComponent({
    setup() {
        const { $axios } = useContext();
        const posts = useAsync<Post[]>(() =>
            $axios
                // $getでPost[]が返ってくる予定
                .$get("https://jsonplaceholder.typicode.com/posts/")
                .then(response => {
                    // ここでresponseの型チェック!!
                    if (implementsPosts(response)) {
                        return response;
                    } else {
                        throw new Error('responseの型がPost型と異なります。');
                    }
                })
        );

        return {
            posts
        };
    },
})
</script>

もっときれいに書けそうな気がするけど...
間違っている点・見づらい点などございましたら、お手数ですがご教示いただければ幸いです!

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?