Microsoft/TypeScript

Suggestion: stricter operators

Open

#7 989 ouverte le 10 avr. 2016

Voir sur GitHub
 (14 commentaires) (15 réactions) (0 assignés)TypeScript (6 726 forks)batch import
Effort: ModerateHelp WantedSuggestion

Métriques du dépôt

Stars
 (48 455 stars)
Métriques de merge PR
 (Merge moyen 6j 17h) (9 PRs mergées en 30 j)

Description

Currently operators like "+" are defined such that they match their semantics in JS. The below are all allowed by the compiler and produce the shown values, even with --strictNullChecks on.

  • 2 + 'a' => "2a"
  • null + 'a' => "nulla" (!)
  • 2 - null => 2

I propose letting users opt in (maybe via some --strictOperators) to strict operator behavior. Concretely I think this means:

  • restrict +, and += to just number and string, e.g. for the former only declare

    function +(a: number, b: number): number;
    function +(a: string, b: string): string;
    
  • restrict - and -= to just number

(any should continue to work as normal, of course.)

Relevant spec section: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#419-binary-operators

See also "Expression operators" in the strictNullTypes change: https://github.com/Microsoft/TypeScript/pull/7140 and in particular this rationale: https://github.com/Microsoft/TypeScript/pull/7140#issuecomment-186432250

This would fall under of "stricter" TypeScript, https://github.com/Microsoft/TypeScript/issues/274 .

Guide contributeur