Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
guyskk opened this issue Dec 14, 2021 · 1 comment
Open
Labels
Bug A bug in TypeScript
Milestone

Comments

@guyskk
Copy link

guyskk commented Dec 14, 2021

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.

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Dec 14, 2021
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Dec 14, 2021
@vincent-yao27
Copy link

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;
    },
  },
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants