Reputation: 14773
Assuming I have an array of objects (simplified version):
const arrObj = [
{ id: "example1", other: "just" },
{ id: "example2", other: "an" },
{ id: "example3", other: "example" }
]
and I want to create a union type out of all id
s
I tried:
const list = arrObj.map((item) => item.id) as const;
type ids = typeof list[number];
But this does not work as it seems I cannot create the array dynamically:
A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.
The desired type output should be: "example1" | "example2" | "example3"
Upvotes: 0
Views: 37
Reputation: 54698
const arrObj = [
{ id: "example1", other: "just" },
{ id: "example2", other: "an" },
{ id: "example3", other: "example" }
] as const
type myIds = typeof arrObj[number]['id']
Upvotes: 1