Add proxy style syntax
codeandcats opened this issue · comments
We use ts-optchain
at work and I actually don't mind it's syntax. It has a couple small advantages:
- When you're ready to evaluate the last part of the property chain you simply call it like a function. This is a natural place to be able to specify a default value without using the
||
operator.
import { oc } from 'ts-optchain';
interface Person {
addresses?: Address[];
}
interface Address {
line1: string;
line2: string;
state: string;
postcode: string;
country: string;
}
const person: Person = {};
const addressLine1 = oc(person).addresses[0].line1('');
Although admittedly, this does mean you can forget to call that last property!
const addressLine1 = oc(person).addresses[0].line1; // Whoops 🤦♂️
- More importantly...continuing with the above example, if you were to use the rename command in VS Code (or likely any IDE that relies on the TypeScript language service for refactoring) to rename the
line1
property in theAddress
interface tostreet1
, the IDE will automatically update the reference toline1
in theoc
call. However if you did the same thing and you were usinggetProp
it would not update the'line1'
string literal. It would simply start showing an error. So admittedly the dev experience withtyped-get-prop
is not quite as nice asts-optchain
in that regard.
I'm wondering if we should allow a similar style with typed-get-prop
so that when you pass in a single parameter, it returns a proxied version of the object.
const addressLine1 = getProp(person, 'addresses', 0, 'line1') || '';
const addressLine2 = getProp(person).addresses[0].line2('');
Dunno, keen to hear your thoughts.