Skip to content

Commit 4bd57c8

Browse files
authored
feat: support typeof expression (prettier#315)
1 parent 56304fb commit 4bd57c8

File tree

3 files changed

+93
-68
lines changed

3 files changed

+93
-68
lines changed

src/transform-node.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -416,15 +416,35 @@ class Transformer extends Source {
416416
);
417417
}
418418

419-
if (node instanceof angular.PrefixNot) {
419+
const isPrefixNot = node instanceof angular.PrefixNot;
420+
if (isPrefixNot || node instanceof angular.TypeofExpression) {
420421
const expression = this.#transform<babel.Expression>(node.expression);
422+
423+
const operator = isPrefixNot ? '!' : 'typeof';
424+
let { start } = node.sourceSpan;
425+
426+
if (!isPrefixNot) {
427+
const index = this.text.lastIndexOf(operator, start);
428+
429+
// istanbul ignore next 7
430+
if (index === -1) {
431+
throw new Error(
432+
`Cannot find operator ${operator} from index ${start} in ${JSON.stringify(
433+
this.text,
434+
)}`,
435+
);
436+
}
437+
438+
start = index;
439+
}
440+
421441
return this.#create<babel.UnaryExpression>(
422442
{
423443
type: 'UnaryExpression',
424444
prefix: true,
425-
operator: '!',
445+
operator,
426446
argument: expression,
427-
start: node.sourceSpan.start, // !
447+
start,
428448
end: getOuterEnd(expression),
429449
},
430450
{ hasParentParens: isInParentParens },
@@ -535,6 +555,7 @@ class Transformer extends Source {
535555
// SafeCall
536556
// EmptyExpr
537557
// PrefixNot
558+
// TypeofExpression
538559
function transform(node: angular.AST, text: string): NGNode {
539560
return new Transformer(node, text).node;
540561
}

tests/helpers.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ const KNOWN_AST_TYPES = [
156156
'ImplicitReceiver',
157157
'KeyedRead',
158158
'SafeKeyedRead',
159+
'TypeofExpression',
159160
'KeyedWrite',
160161
'LiteralArray',
161162
'LiteralMap',

0 commit comments

Comments
 (0)