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

Enhancement: Add UnionKeys #368

Open
Beraliv opened this issue Apr 8, 2023 · 0 comments
Open

Enhancement: Add UnionKeys #368

Beraliv opened this issue Apr 8, 2023 · 0 comments
Labels
enhancement New feature or request v10.1

Comments

@Beraliv
Copy link
Collaborator

Beraliv commented Apr 8, 2023

What

I propose type UnionKeys<UnionType>:

  • to infer all keys of UnionType
  • to support unions

Examples

A type-safe setting value when union is used:

type LogOptions =
  | { action: "openBlogPage"; data: { startTime: number } }
  | { action: "likeVideo"; data: { videoSrc: string } }
  | { action: "closeBlogPage"; data: { readingTime: number } };

const setLogOptions = <TKey extends UnionKeysOf<LogOptions>, TValue = TKey extends keyof LogOptions ? LogOptions[TKey] : never>(
    option: LogOptions,
    key: TKey,
    value: TValue,
) => {
    (option as Record<string, unknown>)[key] = value;
}

declare const option: LogOptions;

setLogOptions(option, 'action', 'openBlogPage');
setLogOptions(option, 'data', {startTime: 1});

Additional Info

TS Playground – https://tsplay.dev/NnE8xw

@Beraliv Beraliv added the enhancement New feature or request label Apr 8, 2023
@Beraliv Beraliv added the v10.1 label May 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request v10.1
Projects
None yet
Development

No branches or pull requests

1 participant