最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

Here is the live demo: =/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

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

Share Improve this question asked Sep 6, 2020 at 22:39 JojiJoji 5,68611 gold badges58 silver badges118 bronze badges 3
  • It should read / be read as: “.. array [literal], or object literal.” – user2864740 Commented Sep 6, 2020 at 22:45
  • 2 The "literal" qualifier refers to all of string, number, array and object here. – Bergi Commented Sep 6, 2020 at 22:47
  • 1 you can do .map(... as const) which will result in an implicit const a:{ readonly label: Keys; readonly id: string; }[] – Thomas Commented Sep 6, 2020 at 22:54
Add a ment  | 

2 Answers 2

Reset to default 2

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 piler 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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论