Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String + - operators #7019

Closed
tomijah opened this issue Feb 11, 2016 · 2 comments
Closed

String + - operators #7019

tomijah opened this issue Feb 11, 2016 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@tomijah
Copy link

tomijah commented Feb 11, 2016

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

Above code causes no compile errors. Is this expected?

@weswigham
Copy link
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.

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Feb 11, 2016
@mhegazy mhegazy closed this as completed Feb 11, 2016
@tomijah
Copy link
Author

tomijah commented Feb 12, 2016

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));
    }
  }
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants