TypeScriptGenerics and advanced types
Indexed access types T[K]
Retrieves the type of a field from another type, just like reading a property from an object.
Example
#TypeScript
interface Course {
title: string
level: 'easy' | 'hard'
lessons: { title: string; minutes: number }[]
}
type Level = Course['level']
// type Level = "easy" | "hard"
type Lesson = Course['lessons'][number]
// type Lesson = { title: string; minutes: number }
const lesson: Lesson = { title: 'Intro', minutes: 5 }
const level: Level = 'easy'
console.log(level, lesson.minutes)Result
easy 5
Definition and usage
#An indexed access type Type["field"] returns the type of a specific field: for Student["level"] that would be number. You can also pass a union of keys, or keyof, to get a union of the types of all the fields.
This keeps helper types always in sync with the source type. If you change the type of a field in Student, every place that uses Student["level"] updates automatically.
From arrays you can get the element type with Array[number], which combined with as const lets you derive a union of values from a list.
Syntax
#Syntax
type FieldType = Type["field"]
type Element = Array[number]Good practices
#- Derive helper types from source types with
T["field"], instead of copying definitions. - The notation
typeof LIST[number]withas constgives a union of all the array’s values.
Related entries
#Spotted a mistake or missing an example? Write to us.