LoginSignup
5
3

More than 1 year has passed since last update.

Vue3の単一ファイルコンポーネント上のTypeScript書き方まとめ

Last updated at Posted at 2022-10-26

はじめに

実務でVue3 × Compositon API × TypeScriptを扱ってきて、よく使う型付けの方法をまとめました。Vue3でプロジェクトを作成してTypeScriptを初めて扱う方の役に立てる記事を残そうと思います。
TypeScriptの記事はたくさんありますが、情報が古かったり小難しい説明がされていて結局どうやって書けばいいか分からないことも多いと思います。
いいからVue3 × Compositon API × TypeScriptの書き方教えてくれ! と思って記事を行ったり来たりしている方におすすめです。

この記事の対象者

  • TypeScript初心者
  • Vue3 × Compositon API × TypeScriptでプロジェクトを作成している人
  • Vue3の単一ファイルコンポーネント(.vue)上でTypeScriptを扱う方

以下単一ファイルコンポーネント上のTypeScript書き方まとめ

TypeScriptExample.vue
<script setup lang="ts">
import { ref } from 'vue';

// テキスト
const stringSample = ref<string>();
stringSample.value = 'string';

// 数字
const numberSample = ref<number>(1);
numberSample.value = 2;

// 配列(型単体)
const arrayExample = ref<number[]>([1, 2, 3]);
arrayExample.value.push(4);

// 配列(型複数)
const mixArrayExample = ref<(number | string)[]>([1, 'string']);

// 配列(ジェネリクス)
const genericsArrayExample = ref<Array<string | number>>([2, 'apple']);

// 連想配列 キー名が決まっている場合
const fixedKeyDictionaryExample = ref<{
    name: string,
    count: number,
    unnecessary?: string
}>({
    'name': 'a',
    'count': 1,
});

// 連想配列 キー名が決まっていない場合
const randomKeyDictionaryExample = ref<{
    [key: string]: string | number
}>({
    'a': 1,
    'b': 'cc',
});

// DOM要素
const domExample = ref<HTMLElement | null>();
domExample.value = document.querySelector<HTMLElement>('.typescript-sample');

// interface
interface myInterface {
    name: string | null;
    count: number;
    isSet?: boolean;
    info: {
        status: string;
    } | null;
};
const interfaceExample = ref<myInterface[]>(
    [
        { name: 'test1', count: 1, info: { status: 'ok' } },
        { name: 'test2', count: 2, isSet: true, info: null }
    ]
);

// nullable対応
interface nullableInterface {
    title: string;
};
let nullableExample!: nullableInterface;
// let nullableExample: nullableInterface | undefined と同義 

// 戻り値が無い関数
const notReturnFunction = (x: string, y?:number): void => {
    console.log(x, y);
};

// 戻り値がある関数
interface returnFunctionInterface {
    title: string;
};
const returnFunction = (value: returnFunctionInterface): string => {
    return value.title;
};
</script>

以上になります。そのうち説明を追記していきます。

Twitterもやってます。

5
3
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
5
3