Skip to content
This repository has been archived by the owner on Feb 26, 2021. It is now read-only.

Fix order of operations with ternary operations #46

Merged
merged 4 commits into from
Jul 31, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/__tests__/ts-optchain-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,10 @@ describe('ts-optchain', () => {
const fn = <K extends { prop: string }>(v: K) => oc(v).prop();
expect(fn({prop: 'foo'})).toEqual('foo');
});

it('ternary order of operations', () => {
expect(
(oc('')('') ? 'bar' : 'bar')
).toEqual('bar');
});
});
5 changes: 3 additions & 2 deletions src/transform/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ function visitNodeAndChildren(node: ts.Node, program: ts.Program, context: ts.Tr
}

function visitNode(node: ts.Node, program: ts.Program): ts.Node {

const typeChecker = program.getTypeChecker();
if (ts.isCallExpression(node)) {
// Check if function call expression is an oc chain, e.g.,
Expand Down Expand Up @@ -53,7 +54,6 @@ function visitNode(node: ts.Node, program: ts.Program): ts.Node {
return _expandOCExpression(node);
}
}

return node;
}

Expand Down Expand Up @@ -119,5 +119,6 @@ function _expandOCExpression(expression: ts.Expression, defaultExpression?: ts.E
ts.createBinary(subExpression, ts.SyntaxKind.ExclamationEqualsToken, ts.createNull()),
);
}
return ts.createConditional(condition, subExpression, defaultExpression || ts.createIdentifier('undefined'));

return ts.createParen(ts.createConditional(condition, subExpression, defaultExpression || ts.createIdentifier('undefined')));
}