Inference not work in object getter when use ThisType with additional fields
guyskk opened this issue Β· comments
Bug Report
π Search Terms
Inference, ThisType, this, getter
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about keyword "this"
β― Playground Link
Playground link with relevant code
π» Code
function myfunc<T>(
options: T & ThisType<T & { name: string }>
): T & { name: string } {
return options as any;
}
const A = myfunc({
get nickname() {
const name = this.name;
return name;
},
getNickname() {
const name = this.name;
return name;
},
});
π Actual behavior
π Expected behavior
expect const name
infer to string type, the same as this.name
.
Similar issue with ThisType
and generic constraints:
Sometimes it's
and sometimes it's
If Record<string, PropertyDefinition>
constraint of generic param T
of function model
is removed, it works as expected
Code
type TypeMap<T> = StringConstructor extends T
? string
: NumberConstructor extends T
? number
: T;
type PropertyDefinition = {
type?: StringConstructor | NumberConstructor;
required?: true;
computed?(): unknown;
};
type Expanded<T> = T extends infer U ? { [P in keyof U]: U[P] } : never;
type DeriveType<T> = T extends { type: infer U }
? TypeMap<U> | (T extends { required: true } ? never : undefined)
: T extends { computed: () => infer U }
? U
: never;
type Entity<T> = Expanded<{
[K in keyof T]: DeriveType<T[K]>;
}>;
function model<T extends Record<string, PropertyDefinition>>(
definition: T & ThisType<Entity<T>>
): T {
return definition;
}
const BillItem = model({
price: { type: Number, required: true },
amount: { type: Number, required: true },
description: { type: String },
total: {
computed() {
return this.amount * this.price;
},
},
});