Issue
Really hitting my head against a wall on this one. I remember working in Angular that TS interfaces can be used to type hint parameters.
I'd like to do the same for props in Vue.
Any ideas? Code is as follows but the check is only made against a standard Object so passing in ANY object is valid:
import Vue from 'vue';
import Person from './../models/Person';
export default Vue.extend({
name: 'HelloWorld',
props: {
person: {
type: Object as () => Person
},
},
});
Interface as follows:
export default interface Person {
firstName: string;
lastName: string;
}
Solution
Yep - so turns out you can't use interfaces. Makes total sense in hindsight when you consider things like type-hinting in PHP7.
The answer is to apply the interface to a class and the type hint using that class instead. With abstraction layers, my worries about having to apply the wrong class to a type hint were unfounded as any class extending or implementing the Person
class will be a valid value to pass to the person
prop.
export default interface NameInterface {
firstName: string;
lastName: string;
}
import NameInterface from './../interfaces/NameInterface';
export default class Person implements NameInterface {
firstName: string;
lastName: string;
constructor( firstName: string, lastName: string ) {
this.firstName = firstName;
this.lastName = lastName;
}
}
<script lang="ts">
import Vue from 'vue';
import Person from './../models/Person';
export default Vue.extend({
name: 'HelloWorld',
props: {
person: {
type: Person
},
},
});
</script>
Answered By - DevLime
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.