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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I get the strict keys for an array somehow? #254

Closed
nandorojo opened this issue Sep 29, 2021 · 2 comments
Closed

Can I get the strict keys for an array somehow? #254

nandorojo opened this issue Sep 29, 2021 · 2 comments

Comments

@nandorojo
Copy link

nandorojo commented Sep 29, 2021

馃崺 Feature Request

I want to get the keys of an array of fixed length, without adding as const to the end of the array. I'm able to get the strict values of it, but not the keys.

Describe the solution you'd like

I'd like to use a type factory to get the readonly keys of an array:

import { List } from "ts-toolbelt";

function makeTheme<T>(t: T): T {
  return t;
}
 
const theme = makeTheme({
  space: [1, 2]
});

type Keys = List.StrictKeys<typeof theme['space']> // "0" | "1"

Describe alternatives you've considered

import { List } from "ts-toolbelt";

function makeTheme<T>(t: T): T {
  return t;
}

// comment in the 'as const' to solve it 馃槙
const theme = makeTheme({
  space: [1, 2] // as const
});

type Space = List.CompulsoryKeys<typeof theme["space"]>;

// this should work
const space: Space = "0";

// this should only allow "0" and "1", but it allows any number
const key: keyof typeof theme["space"] = 10;

Code: https://codesandbox.io/s/ts-toolbelt-test-forked-89wql?file=/src/index.ts:0-396

Screenshots

Screen Shot 2021-09-29 at 3 26 36 PM

Screen Shot 2021-09-29 at 3 26 32 PM

Screen Shot 2021-09-29 at 3 26 27 PM

Thank you!!

@tonivj5
Copy link

tonivj5 commented Sep 29, 2021

Hey! @millsp did it some time ago! You can use Function.Narrow

Some context: microsoft/TypeScript#30680 (comment)

You can check it working here:
https://codesandbox.io/s/ts-toolbelt-test-forked-hnvml?file=/src/index.ts

@nandorojo
Copy link
Author

You just made my day.

@millsp what would we do without you?

@nandorojo nandorojo mentioned this issue Sep 29, 2021
32 tasks
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