简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM