Skip to content

"typeof keyof T" - Getting types of generic object's keys (Make keyof returning value instead of type) #24197

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
3 of 4 tasks
lsagetlethias opened this issue May 17, 2018 · 4 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@lsagetlethias
Copy link

Search Terms

  • typeof keyof
  • "typeof keyof"
  • typeof key in object
  • typeof keyof object

More or less similar issue: #23955

Suggestion

When using a keyof on a type, it returns a list of specific type of each key name.
It could be useful to get the type of the value of each "keyof type".

Use Cases

For reflexion functions, it could be useful to manipulate and typecheck dynamically generic class and type.

Examples

Playground link:
https://www.typescriptlang.org/play/#src=interface%20IModel%20%7B%0D%0A%20%20%20%20id%3A%20number%3B%0D%0A%7D%0D%0A%0D%0Afunction%20foo%3CT%20extends%20IModel%3E(source%3A%20T%2C%20value%3A%20typeof%20keyof%20T%2C%20property%3A%20keyof%20T)%20%7B%0D%0A%20%20%20%20source%5Bproperty%5D%20%3D%20value%3B%0D%0A%7D%0D%0A%0D%0Afoo(%7B%0D%0A%20%20%20%20id%3A%201%2C%0D%0A%7D%2C%20'bar'%2C%20'id')%3B

In this case, I would like when I use the foo() function, to have the second parameter to provide dynamically the type of values set by the third parameter (in ctrl+space)

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)
@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label May 17, 2018
@mhegazy
Copy link
Contributor

mhegazy commented May 17, 2018

here is the correct use of keyof:

function foo<T extends IModel, K extends keyof T>(source: T, value: T[K], property: K) {
    source[property] = value;
}

@lsagetlethias
Copy link
Author

lsagetlethias commented May 17, 2018

Wow thank you very much @mhegazy, quite complex.
Can you link me where it is in the documentation ?

@mhegazy
Copy link
Contributor

mhegazy commented May 17, 2018

@lsagetlethias
Copy link
Author

Great, thank you. Sorry for missing that part.

@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

2 participants