rimeto/ts-optchain

Bug when property is null

Closed this issue · 1 comments

Let's have this simple example

import { oc } from 'ts-optchain';

interface User {
  details?: {
    description?: string;
  };
}

const user: User = { details: undefined };
const resolvedDescription = oc(user).details.description();
console.log(resolvedDescription);

This thing works correctly so that resolvedDescription is undefined.

But let's see what happens when we change to null

import { oc } from 'ts-optchain';

interface User {
  details?: {
    description?: string;
  };
}

const user: User = { details: null }; // <-- This is now null
const resolvedDescription = oc(user).details.description();
console.log(resolvedDescription);

The code will crash.

/Users/lol/projects/ts-optchain-bug/node_modules/ts-optchain/dist/index.js:41
            return oc(obj[key]);
                         ^

TypeError: Cannot read property 'description' of null
    at Object.get (/Users/lol/projects/ts-optchain-bug/node_modules/ts-optchain/dist/index.js:41:26)
    at Object.<anonymous> (/Users/lol/projects/ts-optchain-bug/index.js:5:57)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3

I am pretty sure this is NOT how optional chaining should work. I think it should also work with nulls right? At least the proposal is saying it should handle nulls too https://github.com/tc39/proposal-optional-chaining#base-case

I guess the problem could be in this line https://github.com/rimeto/ts-optchain/blob/master/src/index.ts#L111
Looks like when I edit that ternary to data || defaultValue it works :)