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

Issue when combining distributive conditional types combined with generic method #31275

Closed
jeroenvervaeke opened this issue May 6, 2019 · 3 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@jeroenvervaeke
Copy link

TypeScript Version: 3.5.0-dev.20190504

Search Terms:

  • distributive conditional types
  • condition types
  • distributive conditional types generics

Description
I've been trying to make a generic function which receives and object T and receives a string property name of that object T.

I used https://www.typescriptlang.org/docs/handbook/advanced-types.html as an example (section: Distributive conditional types)

I've come up with a solution that works without generics, but when I change the explicit types to a generic type typescript won't compile.

Code

export type TypedPropertyNames<T, P> = { [K in keyof T]: T[K] extends P ? K : never }[keyof T];
export type StringPropertyNames<T> = TypedPropertyNames<T, string>;

interface Test {
  test: string;
}

function non_generic(form: Test, field: StringPropertyNames<Test>): string {
  return form[field]; // This compiles
}

function generic<T>(form: T, field: StringPropertyNames<T>): string {
  return form[field]; // This won't compile
}

Expected behavior:
The generic example compiles

Actual behavior:
The generic example doesn't compile

Playground Link:
Playground

Related Issues:
#30295
#29505
#29662

@jcalz
Copy link
Contributor

jcalz commented May 7, 2019

For cross-referencing purposes: associated Stack Overflow question

@ahejlsberg
Copy link
Member

This is beyond the reasoning capabilities of the type checker. The checker would need to understand that StringPropertyNames<T> is constrained such that T[StringPropertyNames<T>] is constrained to type string. We don't produce such transitive constraints and it would definitely be complex to do so. I'm afraid you'll need a type assertion for this one.

@ahejlsberg ahejlsberg added the Design Limitation Constraints of the existing architecture prevent this from being fixed label May 8, 2019
@jcalz
Copy link
Contributor

jcalz commented Nov 18, 2019

related: #30728

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants