microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

Home Page:https://www.typescriptlang.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Inference not work in object getter when use ThisType with additional fields

guyskk opened this issue Β· comments

commented

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

this.name is string:
image-20211215011426242

but const name is any:
image-20211215011440514

πŸ™‚ 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;
    },
  },
});