1. Arrays of objects
It can be useful to get a type from an array of values so that you can use it as
Let’s take this simple, although contrived, example using const assertions:
We will use const assertions (TypeScript 3.4+) to remove the duplication.
const sample_array= ["apple", "cat", "animal"] as const
// const sample_array: readonly ["apple", "cat", "animal"]
Getting a type from our array
Now we can get a type from our animals
array using typeof
:
const sample_array = ["apple", "cat", "animal"] as const;
type ICustomType = typeof sample_array[number]
// type ICustomType = 'apple' | 'cat' | 'animal'
2. Arrays of objects
const sample_array = [
{ year: 2021, value: 'The Little Things' },
{ year: 2022, value: 'Avatar: The Way of Water' },
{ year: 2023, movie: 'A Quiet Place: Day One' }
] as const
type ICustomType = typeof sample_array[number]['year']
// type ICustomType = 2021 | 2022 | 2023