Vue 같은 타입 서포팅의 간단한 버전을 구현하라.
(Vue.extends나 defineComponent와 유사한) 함수명 SimpleVue에 의해, computed와 method 내부의 this 타입을 적절하게 추론해야한다.
data는 this context를 드러내는 객체를 반환하지만, 당신은 다른 computed values나 methods에 접근할 수 없다.
computed는 this를 맥락을 가지는 함수이며, 몇몇 계산을 하고 결과값을 반환한다. computed 결과는 함수 대신에 순수한 반환 값으로써 맥락(this)을 드러내야 한다.
methods도 this를 맥락으로 받아야 하는 함수들의 객체이다.
methods는 data,computed, 다른 method들에 의해 드러난 필드에 접근할 수 있어야 한다. computed와 다른 점은 method는 함수 그 자체로 드러나져야 한다.
SimpleVue의 반환은 임의적일 수 있다.
Implement a simpiled version of a Vue-like typing support.
By providing a function name SimpleVue (similar to Vue.extend or defineComponent), it should properly infer the this type inside computed and methods.
In this challenge, we assume that SimpleVue take an Object with data, computed and methods fields as it's only argument,
data is a simple function that returns an object that exposes the context this, but you won't be accessible to other computed values or methods.
computed is an Object of functions that take the context as this, doing some calculation and returns the result. The computed results should be exposed to the context as the plain return values instead of functions.
methods is an Object of functions that take the context as this as well. Methods can access the fields exposed by data, computed as well as other methods. The different between computed is that methods exposed as functions as-is.
The type of SimpleVue's return value can be arbitrary.
type GetComputed<C> = C extends Record<string, (...args: any[]) => any>
? { [S in keyof C]: ReturnType<C[S]> }
: never
declare function SimpleVue<D, C, M>(
options: {
data: (this:void) => D,
computed: C,
methods: M,
} & ThisType<D & M & GetComputed<C>>
): any
문제 제작자의 풀이를 많이 참고했다.
제네릭을 통해 인자의 각 프로퍼티 값에 해당하는 D와 C,M을 추출해낸다.
이후 추출한 값을 this로 지정할 수 있도록 ThisType을 사용한다.
이때, C는 값이 아닌 객체 내부의 함수 return값을 사용해야하므로, 별도의 조치를 취해준다.
그리고,D에서는 C나 D의 값을 참조할 수 없으므로, this를 명시적으로 void로 설정해준다.
난이도 Medium에서는 본 적이 없던 ThisType이 등장했다.
ThisType은 제네릭으로 들어온 값으로 this를 명시적으로 선언해준다.
https://github.com/type-challenges/type-challenges/issues/11
https://www.typescriptlang.org/ko/docs/handbook/utility-types.html#thistypetype