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
Not exactly what you want but you can hack around this with the typof keyword but only if you have a var that is declared as your interface type like below. Note that I think what you did in your last codeblock is a lot better :)
interface ExerciseData {
id : number;
name : string;
vocabulary : {
from : string;
to : string;
}[];
}
var x: ExerciseData;
var vocabs : typeof x.vocabulary[];
I found it's working in the next way these days:
interface User {
avatar: string;
}
interface UserData {
someAvatar: User['avatar'];
}
very useful if you don't want to export all the things.