Skip to content

String + - operators #7019

Closed
Closed
@tomijah

Description

@tomijah

var a = -"test";
var b = "test1" + + "test2"

Above code causes no compile errors. Is this expected?

Activity

weswigham

weswigham commented on Feb 11, 2016

@weswigham
Member

a is NaN, b is the string "test1NaN". This is valid - unary minus and unary plus (your second line is a binary plus with a unary plus in the right hand side) operators coerce strings to numbers. (And binary + with a string as the first argument coerces numbers to strings!) For example, +"23" will be the number 23.

So yeah, that this is allowed is expected - and also somewhat common, it's actually (usefully) used in one place within the TS compiler (inside the parser). It's somewhat more reliable than doing Number("023") and definitely more reliable than parseInt("023").

As far as types are concerned, it all checks out - however, if you're looking to forbid this kind of usage of unary plus/minus in your own code, I can recommend writing a tslint rule for it.

added
QuestionAn issue which isn't directly actionable in code
on Feb 11, 2016
tomijah

tomijah commented on Feb 12, 2016

@tomijah
Author

Ty.

import * as ts from 'typescript';
import * as Lint from 'tslint/lib/lint';

export class Rule extends Lint.Rules.AbstractRule {
  public static FAILURE_STRING = 'string unary plus operator not allowed';

  public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    const walker = new NoStringunaryOperatorsWalker(sourceFile, this.getOptions());
    return this.applyWithWalker(walker);
  }
}

class NoStringunaryOperatorsWalker extends Lint.RuleWalker {
  protected visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression) {
    const sourceFile = this.getSourceFile();
    const position = node.getStart(sourceFile);
    if (node.operator === ts.SyntaxKind.PlusToken && node.operand.kind === ts.SyntaxKind.StringLiteral) {
      this.addFailure(this.createFailure(Math.min(position, this.getLimit()), 0, Rule.FAILURE_STRING));
    }
  }
}
locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @tomijah@weswigham@mhegazy

        Issue actions

          String + - operators · Issue #7019 · microsoft/TypeScript