TypeScript 環境で Vue.js 2.x を使う時にハマったところを書いていく
自分用。都度追記していきたい。
data に型を持たせる
import Vue from 'vue'
type Data = {
title: string,
description: string,
fruits: {
name: string,
price: number
}[]
}
export default Vue.extend({
name: 'FreshFruitsListPage',
data: (): Data => {
return {
title: 'Fresh fruits!',
description: 'What is the most fresh fruit on this season?',
fruits: [
{name: 'Water meron', price: 1000 },
{name: 'Kiwifruit', price: 500 },
{name: 'Loquat', price: 300 },
]
}
},
methods: {
showSomething() {
console.log(this.fruits[0].name)
}
}
})
props に型を持たせる
2.5以降では propsに String
, Number
などの型がつけられる。
Array
、 Object
は any[]
any
になってしまう。( Vue + TypeScriptでpropsのObjectやArrayに型をつける より)
その場合の解決方法。型キャストが使える。
とてもとても乱暴に書くと
{Vue.js の型} as PropType<{TypeScriptの型}>
import Vue, { PropType } from 'vue'
interface Fruits {
name: string
price: number
}
export default Vue.extend({
name: 'FruitPage',
props: {
title: {
type: String as PropType<string>,
default: ""
},
Fruits: {
type: Object as PropType<Fruits>
}
}
})
自身の値や関数を this で参照できない。エディタに怒られる。
慣れてないと意外に見落としがちだが、ちゃんとVue.extends()
を使っているか確認。
$emit
とかでエラーが表示される際も同様。