LoginSignup
9
5

More than 3 years have passed since last update.

TypeScript+Vue.jsの環境でnullableなpropsを指定する

Posted at

TypeScript+Vue.jsの環境でVue.jsのコンポーネントでpropsを使っているときに、nullableなtype指定をどうやってやるかを説明します。

結論

Typescriptの方の型指定だけnullableであることを明示します。

title.vue

<template>
<h1>{{ title }}</h1>
</template>

<script lang="ts">
import { createComponent, SetupContext } from '@vue/composition-api'

export default createComponent({
    props: {
        title: {
            type: String as () => string | null,
            default: null
        }
    }
})
</script>

そもそもなのですが、Vue.jsのpropsはすべてnullableなので、nullableにするときに[String, null]というようにnullをpropsのtypeに書く必要はありません。

よって、TypeScript側にだけnullableだということを教えればよいです。

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