Skip to content

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

Closed
@nandorojo

Description

@nandorojo

🍩 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!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions