Skip to content

Cannot use keyof on one type to index fields in another type with the same keys, but different types for the values #46928

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

Closed
dbinnersley opened this issue Nov 26, 2021 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@dbinnersley
Copy link

dbinnersley commented Nov 26, 2021

Bug Report

πŸ”Ž Search Terms

keyof types

πŸ•— Version & Regression Information

4.2.3 when running on my own machine
4.5.2 when running on ts playground

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

export type KeysOfType<T, U, B = false> = {
  [P in keyof T]: B extends true
    ? T[P] extends U
      ? U extends T[P]
        ? P
        : never
      : never
    : T[P] extends U
    ? P
    : never;
}[keyof T];

export type BigIntKeys<T> = KeysOfType<T, bigint, true>

export type CompatType<T> = Omit<T, BigIntKeys<T>> &
  {
    [Property in BigIntKeys<T>]: string;
  };

export function compatModel<T>(model: T): CompatType<T> {
  const compat: Partial<CompatType<T>> = {};
  for (const k of Object.keys(model) as Array<keyof T>) {
    const v = model[k];
    compat[k] = typeof v === "bigint" ? v.toString() : v;
  }
  return compat as CompatType<T>;
};

πŸ™ Actual behavior

The final compat[k] shows a type error indicating Type 'keyof T' cannot be used to index type 'Partial<CompatType<T>>

πŸ™‚ Expected behavior

The keys from T should be allowed to index CompatType<T> since the keys contained in both of the types are identical. The only difference is the values which have changed from bigints to strings.

@jcalz
Copy link
Contributor

jcalz commented Nov 26, 2021

Duplicate of #28884.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Nov 29, 2021
@RyanCavanaugh
Copy link
Member

Nice find @jcalz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants