tomSawkins / typed-get-prop

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add proxy style syntax

codeandcats opened this issue · comments

commented

We use ts-optchain at work and I actually don't mind it's syntax. It has a couple small advantages:

  1. 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 🤦‍♂️
  1. 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 the Address interface to street1, the IDE will automatically update the reference to line1 in the oc call. However if you did the same thing and you were using getProp it would not update the 'line1' string literal. It would simply start showing an error. So admittedly the dev experience with typed-get-prop is not quite as nice as ts-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.