type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

Proposal: KeysOfUnion, `keyof` Union type

Open ajitzero opened this issue 3 years ago • 6 comments

Context: https://stackoverflow.com/q/49401866

interface Foo {
  foo: string;
}

interface Bar {
   bar: string;
}
type Batz = Foo | Bar;
type AvailableKeysFoo  = keyof Foo;  // Works as expected
type AvailableKeysBatz = keyof Batz; // Gives 'never', expected (keyof Foo | keyof Bar)

Solution: https://stackoverflow.com/a/49402091

type Batz = Foo | Bar;
type KeysOfUnion<T> = T extends T ? keyof T : never;

type AvailableKeys = KeysOfUnion<Batz>; // keyof Foo | keyof Bar -> "foo" | "bar"

ajitzero avatar Mar 22 '22 16:03 ajitzero

I am willing to open a PR with this change if this is fine "as-is". This solution belongs to the OP in the linked StackOverflow answer.

ajitzero avatar Mar 22 '22 16:03 ajitzero

This type is being added internally in https://github.com/sindresorhus/type-fest/pull/259/files#diff-49eaac4718b21c2c3d9ed8024c97600050979229a82a0255cc3c538e36350131R45-R53. After that PR is merged, we can expose it. If you want to see this happen sooner than later, help with reviewing the referenced PR is welcome.

sindresorhus avatar Mar 22 '22 17:03 sindresorhus

This can now be done: https://github.com/sindresorhus/type-fest/blob/f171b707fdbc9b7e895a34374ee865272a9b1d5a/source/internal.d.ts#L46-L53

sindresorhus avatar Jun 30 '22 16:06 sindresorhus

@sindresorhus Thank you! I think with this the pending changes would be documentation?

  • [ ] Mention/link in Repository README
  • [ ] Update on paka.dev? Or is that auto-generated from the TSDoc?

I can take this up this weekend if you can point to a relevant docs PR.

ajitzero avatar Jul 01 '22 18:07 ajitzero

Read: https://github.com/sindresorhus/type-fest/blob/main/.github/contributing.md#submitting-a-new-type

It needs tests and expanded doc comments.

sindresorhus avatar Jul 02 '22 11:07 sindresorhus

Update on paka.dev? Or is that auto-generated from the TSDoc?

Auto-generated

sindresorhus avatar Jul 02 '22 11:07 sindresorhus