Joji
Joji

Reputation: 5646

TypeScript: is there a way to do const assertions on the array return by Object.values?

Here is the live demo: https://codesandbox.io/s/vigorous-rgb-u860z?file=/src/index.ts

enum Keys {
  One = "one",
  Two = "two"
}

const a = Object.values(Keys).map((value, index) => ({
  label: value,
  id: String(index)
})) as const;

Here is the error message

A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.

I am not sure what I am missing here since Object.values indeed returns an array. Why can't I make const assertion on it

Upvotes: 6

Views: 4805

Answers (2)

Mingwei Samuel
Mingwei Samuel

Reputation: 3282

The reason you can't do this is because the left hand side X of a const assertion X as const has to be a literal value that the TypeScript compiler knows.

So I assume your end goal is that you want to have the full type of A. Without any special stuff you get this:

const a: {
    label: Keys;
    id: string;
}[]

Now if you want to get this:

const a: [
    {
        label: "one";
        id: "0";
    },
    {
        label: "two";
        id: "1";
    }
]

This isn't really possible since you're depending on Object.values iteration order. Which is defined by ES2015, but typescript types don't "know" about it.

With some simple fancy types you can get to:

type EnumEntry<T> = T extends any ? { label: T, id: string } : never;

const a: EnumEntry<Keys>[] = Object.values(Keys).map((value, index) => ({
  label: value,
  id: String(index)
}));
const a: ({
    label: Keys.One;
    id: string;
} | {
    label: Keys.Two;
    id: string;
})[]

But that's the best I think we can do without depending on how typescript orders the types.

Upvotes: 2

Porcellus
Porcellus

Reputation: 579

It's not exactly a const assertion, but you could do something like: as ReadonlyArray<{label: Keys, id: string}> instead of as const.

Playground link

Upvotes: 1

Related Questions