TypeScript: Reference subtype of type definition (interface)

You can reference interface subtypes using lookup types, added in TypeScript 2.1:

interface ExerciseData {
    id: number;
    name: string;
    vocabulary: Array<{
        from: string;
        to: string;
    }>;
}

type Name = ExerciseData['name']; // string

These lookup types can also be chained. So to get the type of a vocabulary item you can do this:

type Vocabulary = ExerciseData['vocabulary'][number]; // { from: string; to: string; }

Or with even more chaining, the from field:

type From = ExerciseData['vocabulary'][number]['from']; // string

For complex scenarios it’s also possible to base the lookup type on another type. For example, on a string literal union type:

type Key = 'id' | 'name';
type FieldTypes = ExerciseData[Key]; // number | string

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)