Discover various methods to determine the type of a property within an object. While some have been mentioned, let's delve deeper into this topic.
A helpful tip: incorporating Conditional Types
can assist in avoiding type errors, depending on the specific requirements at hand.
1. Utilizing Conditinal Types
with infer
Imagine having the following object:
const student = {
name: 'John Doe',
age: 22,
dormitory: true
}
The objective is to ascertain the type of age
(for instance)
type AgeTypeUsingInfer<T> = T extends {age: infer K} ? K : never;
type AgeType = AgeTypeUsingInfer<typeof student>
The resultant AgeType
will correctly indicate a number
type.
If an object lacking the age
property is used, the return type will be never
.
const musician = {
art: 'Pop',
city: 'Gotham'
}
type MusicianAgeType = AgeTypeUsingInfer<typeof musician>
In such instances, MusicianAgeType
will resolve as never
sans any type errors.
2. Implementing Conditional Types
with Indexed Access
type AgeTypeUsingConditionalTypesAndIndexedAccess<T> = T extends {age: any} ? T['age'] : never;
type AgeType2 = AgeTypeUsingConditionalTypesAndIndexedAccess<typeof student>; // number
type MusicianAgeType2 = AgeTypeUsingConditionalTypesAndIndexedAccess<typeof musician>; // never
3. Employing Indexed Access
type AgeTypeUsingIndexedAccess<T extends {age: any}> = T['age'];
type AgeType3 = AgeTypeUsingIndexedAccess<typeof student>; // number
type MusicianAgeType3 = AgeTypeUsingIndexedAccess<typeof musician>; // type error
Based on your needs, you can designate the type as never
, or permit a type error to promptly emerge if an incompatible object is provided.
This explanation aims to aid in your programming pursuits... happy coding :)