Strongly-typed function to get a nested & potentially null/undefined property value.

Install
npm install typed-get-prop --save
Usage
import { getProp } from 'typed-get-prop';
const movie: Movie = {
title: 'The Matrix',
year: 1999
cast: [
{
name: 'Keanu Reeves',
characters: [{
name: 'Neo'
}]
},
{
name: 'Carrie-Anne Moss',
characters: [{
name: 'Trinity'
}]
}
]
};
const year = getProp(movie, 'year');
const trinity = getProp(movie, 'cast', 1, 'characters', 0, 'name');
Why do I need this?
-
Because getting a nested property value can be error-prone when parent properties can be null
or undefined
.
const movie: Movie = {
title: 'Fight Club',
year: 1999
};
const leadActor = movie.cast[0];
const leadActor = getProp(movie, 'cast', 0);
-
Unlike most (if not all?) other property getter libraries on NPM, typed-get-prop
will complain at design/compile-time if you try to access a property of a typed object that doesn't exist in the model.
const movie: Movie = {
title: 'The Matrix',
year: 1999
cast: [
{
name: 'Keanu Reeves',
characters: [{
name: 'Neo'
}]
}
]
};
const leadActor = getProp(movie, 'actors', 0);
-
Again, unlike other property getter libraries, typed-get-prop
will correctly infer types of properties.
const movie: Movie = {
title: 'The Matrix',
year: 1999
cast: [
{
name: 'Keanu Reeves',
characters: [{
name: 'Neo'
}]
}
]
};
const year = getProp(movie, 'year');
Comparison with other npm libraries
Contributing
Got an issue or a feature request? Log it.
Pull-requests are also welcome.