Example:
type Options<Data, Methods> = {
data: (this: void) => Data;
methods: Methods & ThisType<Data & Methods>;
};
declare function defineComponent<Data, Methods>(
options: Options<Data, Methods>
): any;
defineComponent({
data() {
return {
amount: 10,
}
},
methods: {
asdasd: 'hi', // !!! no error here
checkThis() {
console.log(this.amount); // "this" has correct type
},
},
});
“this” has following type:
{
amount: number;
} & {
asdasd: string;
checkThis: () => void;
}
It is exactly what I need.
Now I want to fix problem with type checking. Methods should be only functions:
type MethodsOption = Record<string, Function>;
type Options<Data, Methods extends MethodsOption> = {
data: (this: void) => Data;
methods: Methods & ThisType<Data & Methods>;
}
declare function defineComponent<Data, Methods extends MethodsOption>(
options: Options<Data, Methods>
): any;
defineComponent({
data() {
return {
amount: 10,
}
},
methods: {
asdasd: 'hi', // now we have error here, it is OK
checkThis() {
console.log(this.amount); // !!! but "this" here is { this: MethodsOption }
},
},
});
Now there is no more type checking using “this”.
This example is just similar to Vue.js but doesn’t use its code.
How to fix problem with types and save correct ThisType?
I tried to find a solution in the Vue.js source code, but there is nothing special. Also, I tried different ways to fix this in ts, like mapping and others, but nothing worked.