I am using the following type in my TypScript:
interface ExerciseData { id : number; name : string; vocabulary : { from : string; to : string; }[]; }
Now I'd like to create a variable that is of the same type as the attribute vocabulary
, trying the following:
var vocabs : ExerciseData.vocabulary[];
But that is not working. Is it possible to reference to a subtype somehow? Or would I have to do something like this?
interface ExerciseData { id : number; name : string; vocabulary : Vocabulary[]; } interface Vocabulary { from : string; to : string; } var vocabs : Vocabulary[];
Thanks a lot for hints.
Summary. The TypeScript object type represents any value that is not a primitive value. The Object type, however, describes functionality that available on all objects. The empty type {} refers to an object that has no property on its own.
The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object. Type keyword when used for declaring two different types where the variable names declared are the same then the typescript compiler will throw an error.
Interfaces and Inheritance An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
Bookmark this question.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With