Simple Vue
About 1 minTC-Hard
Simple Vue
Problem
Implement a simplified version of a Vue-like defineComponent function that accepts an options object with data, computed, and methods properties. Each of these should have proper access to this:
data()returns a plain objectcomputedcontains functions that return a value;thisshould have access todatafields and othercomputedpropertiesmethodscontains functions;thisshould have access todatafields,computedvalues, and other methods
const instance = SimpleVue({
data() {
return { firstName: 'Type', lastName: 'Challenges', amount: 10 }
},
computed: {
fullName() { return `${this.firstName} ${this.lastName}` }
},
methods: {
hi() { alert(this.fullName.toLowerCase()) }
}
})Solution
The key challenge is that this in each section must refer to different merged contexts.
declare function SimpleVue<D, C extends Record<string, () => any>, M>(options: {
data(this: void): D
computed: C & ThisType<D>
methods: M & ThisType<D & { [K in keyof C]: ReturnType<C[K]> } & M>
}): anyHow it works:
data(this: void)— prevents accidentalthisusage insidedata, since it should be a pure factory.computed: C & ThisType<D>— computed functions can accessdatafields viathis.methods: M & ThisType<D & ComputedValues & M>— methods can access data, computed return values, and other methods.{ [K in keyof C]: ReturnType<C[K]> }— maps each computed property to its return type, simulating how Vue exposes computed as plain properties on the instance.
ThisType<T> is a built-in TypeScript utility that sets the type of this inside an object literal when used with noImplicitThis.
Key Takeaways
ThisType<T>is the standard TypeScript mechanism for typingthisin option/mixin APIs.- Mapped types over
keyof CwithReturnTypelet you "flatten" computed getters into plain properties. - Breaking the problem into independent generic parameters (
D,C,M) allows TypeScript to infer each section independently before combining them.
