typescript
1// type.ts 2 3export interface Fruits { 4 id?: number 5 type: Apple | AppleJam 6} 7 8export interface Apple { 9 rank: number 10 area: string 11 comment: string 12} 13 14export interface AppleJam { 15 area: string 16 comment: string 17}
vue
1<template> 2<!-- 省略 --> 3</template> 4 5<script lang="ts"> 6import { Component, Prop, Vue } from 'nuxt-property-decorator' 7import { Fruits } from './type.ts' 8 9@Component 10export default class AppleItem extends Vue { 11 @Prop() fruitsData!: Fruits 12 13 hoge() { 14 this.fruitsData.type.rank = 1 15 } 16} 17</script> 18
上記のコードの場合に、this.fruitsData.type.rank
でエラーが発生します。
Property 'rank' does not exist on type 'Apple | AppleJam'. Property 'rank' does not exist on type 'AppleJam'.
これはinterface AppleJam
の中にrank
がないためにエラーが発生してるかと思うのですが、このコンポーネントにpropで値を受け取った段階で既にtype
がAppleであることが決まっているので、それを定義したいのですが、書き方がわかりません、、。propで受け取ったオブジェクトの中の型チェックはどのようにやるのでしょうか?
初学者のため、どなたかご教示お願いします。