If you have a type annotation on the const items
declaration in an actual array, you cannot determine the type from the array itself. The type annotation takes precedence over inferring the type from the actual value. However, removing the type annotation allows you to use typeof items
to ascertain its type. You can then utilize indexed access to obtain the type of the symbol
property.
It is important to note that using as const
is necessary to maintain string literal types; otherwise, they will default to just string
.
const items = [
{ id: 1, symbol: "a" },
{ id: 2, symbol: "b" },
] as const;
// Output: "a" | "b"
type Symbols = typeof items[number]['symbol']
By following this approach, you may no longer validate if the array elements are truly of type Item
. To address this, refer to the technique outlined in this alternative answer. I opted for the type parameter S extends string
instead of T extends Item
to eliminate the need for as const
.
function checkItems<S extends string>(arr: (Item & {symbol: S})[]) {
return arr;
}
const items = checkItems([
{ id: 1, symbol: "a" },
{ id: 2, symbol: "b" },
]);
Explore and experiment further with the code using the TypeScript Playground here.