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

Transpose or invert object keys to/from key-like literal values #543

Closed
texastoland opened this issue Jan 13, 2023 · 4 comments
Closed

Transpose or invert object keys to/from key-like literal values #543

texastoland opened this issue Jan 13, 2023 · 4 comments

Comments

@texastoland
Copy link

texastoland commented Jan 13, 2023

I'm not sure whether this would be generally useful. I personally struggled to implement it. Happy to PR but wanted to gauge interest first and document my solution for searchability otherwise:

type Transpose<Obj extends Record<PropertyKey, PropertyKey> | PropertyKey[]> = {
  [Value in Extract<Obj[keyof Obj], PropertyKey>]: keyof {
    [Key in keyof Obj as Obj[Key] extends Value ? Key : never]: never
  }
}

type Letters = ["A", "B", "C", "D", "Etc"]
type Letters2Indexes = Transpose<Letters>
//   ^? type Letters2Indexes = { 5: "length"; A: "0"; B: "1"; C: "2"; D: "3"; Etc: "4"; }

[Playground]

@sindresorhus
Copy link
Owner

What are some practical use-cases for this? I don't really see the use-case without also an actual code implementation, and then you would do so in TS and not need this type.

@sindresorhus
Copy link
Owner

It could also be more type-safe by ensuring the input object values are valid keys.

@texastoland
Copy link
Author

texastoland commented Jan 15, 2023

It could also be more type-safe by ensuring the input object values are valid keys.

Fixed in the description.

What are some practical use-cases for this?

I don't have 1. It was for an unfortunately contrived teaching exercise. I thought it'd be worthwhile to share the implementation (perhaps closing the issue) and reconsider if someone comes looking (like I did) with a better use case.

@texastoland
Copy link
Author

I don't really see the use-case without also an actual code implementation, and then you would do so in TS and not need this type.

Sounds right so I linked it to the invert function in Remeda instead.

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

No branches or pull requests

2 participants