One of the ways to get typescript support inside single file components is to use vue-class-component together with vue-property-decorator.
This enables you to give better typings for your props:
import { Vue, Prop, Component } from "vue-property-decorator";
@Component({
name: 'MyCoolComponent'
})
export default class extends Vue {
@Prop() complexType!: ComplexType
}
But the caveat is that Vue will treat the type as Object
in most cases.
One place where this can be a problem is when using enums.
With the following code:
enum Suit {
Heart = 1,
Spade = 2,
Diamond = 3,
Club = 3
}
...component declaration
@Prop() suit!: Suit;
You will get type checking inside you file, but at runtime you may encounter the following error
[Vue warn]: Invalid prop: type check failed for prop "suit". Expected Object, got Number.
.
This is because under the hood, a typescript enum looks like this (ts playground link):
var Suit;
(function (Suit) {
Suit[Suit["Heart"] = 1] = "Heart";
Suit[Suit["Spade"] = 2] = "Spade";
Suit[Suit["Diamond"] = 3] = "Diamond";
Suit[Suit["Club"] = 3] = "Club";
})(Suit || (Suit = {}));
and when an enum member is passed into the vue component, it thinks it got a number.
The fix I found was to use the following configuration inside the Prop
decorator.
@Prop({
type: Number,
default: null // Use this if the value can be null or undefined
})
suit!: Suit;