admin管理员组文章数量:1433484
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
- 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 implicitconst a:{ readonly label: Keys; readonly id: string; }[]
– Thomas Commented Sep 6, 2020 at 22:54
2 Answers
Reset to default 2The 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
本文标签:
版权声明:本文标题:javascript - TypeScript: is there a way to do const assertions on the array return by Object.values? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745607337a2665910.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论