typescript,resharper,ecmascript-6 , “Variable 'X' can be made constant”, what does 'constant' mean?


“Variable 'X' can be made constant”, what does 'constant' mean?

Question:

Tag: typescript,resharper,ecmascript-6

VStudio or ReSharper is giving me the suggestion below:

enter image description here

What does constant mean in this scenario? If it's a constant in the current method scope, what's the purpose? Methods tend to be small and therefore it shouldn't give any advantage compared to be a regular var?

Please enligten me


Answer:

It's nothing complicated.

It's always better to use const over let (and definitely var), since const makes it a bit easier for other coders, or you when you come back to the same code in the future, to understand what is going on, since you only have to look at the initial assignment to know what the contents of the variable are. Therefore you are encouraged to use it when possible.

It should be noted that though constants can not be reassigned their contents can. So const x = [1]; x[0] = 2; is perfectly valid code, but it screams anti-pattern. There is still the Object.freeze method if you want immutability all the way, although I'd generally only use this for API's, not within methods.

Some compiler optimizations like inlining are possible through the use of const, therefore its use might give you a slight gain in performance in the future when you don't transpile typescript down to ecmascript 5 or lower anymore. I doubt that these optimizations will help within function scopes though.

You can run a performance test of var vs let vs const here: https://jsperf.com/let-vs-var-performance/35. On my laptop OSX 10.10.2 with Firefox 38 const is 3% slower than var (which is fastest) and with Chrome 43 const is 1.28% slower than var. Indicating that there is still some optimization work to be done. Note that const in this performance test is being used within a function scope.


Related:


Update Knockout Observable string in refresh function


javascript,knockout.js,typescript
The code is in typescript and I am trying to show current date time on page load and update that date time on refresh click. In .ts file string that shows date time is declared like this. asOfString: KnockoutObservable<string>; In the constructor it is being set like this, this.asOfString =...

Cannot find external module 'angular2/angular2' - Angular2 w/ Typescript


angularjs,typescript,angular2
I am going through the step by step tutorial on angular.io (Angular 2). I am using typescript. I get the following error when trying to compile: Cannot find external module 'angular2/angular2' using the watch command. main.ts import {Component, View, bootstrap} from 'angular2/angular2'; @Component({ selector: 'my-app' }) @View({ template: '<h1>My first...

ReSharper and NUnit's multiple domains


nunit,resharper
I recently had to enable this option in ReSharper: Use separate AppDomain for each assembly with tests Looking at the NUnit documentation, I suspect the option above executes NUnit with the parameter "domain/multiple", for which "a separate test domain is created for each assembly". Could you please confirm me that...

How to angularjs app.service and $q in typescript


angularjs,typescript,angular-material
I am Very new to typescript and angular Js . I have am not able to find correct answer , my code is given below: export class SidenavController { static $inject = ['$scope', '$mdSidenav']; constructor(private $scope: any,private $mdSidenav: any) { } toggleSidenav(name: string) { this.$mdSidenav(name).toggle(); } loadHelpInfo() { this.helpService.loadAll() .then(function(help)...

TypeScript: workaround for relative reference path?


module,typescript,tsd
My goal is to refer to .d.ts files that I've installed with tsd. The tsd definitions GitHub repository has examples using paths relative to the source file's location: /// <reference path="../typings/tsd.d.ts" /> I find that a potential maintenance issue - if I want to reorganize how my project is organized,...

Angular directive dependency injection - TypeScript


angularjs,typescript
There seem to be a number of ways to create Angular directives in TypeScript. The neatest I've seen is to use a static factory function: module app { export class myDirective implements ng.IDirective { restrict: string = "E"; replace: boolean = true; templateUrl: string = "my-directive.html"; link: ng.IDirectiveLinkFn = (scope:...

Using TypeScript type definitions with Webstorm 10 [duplicate]


node.js,typescript,webstorm
This question already has an answer here: intellisense and code complete for DefinitelyTyped (TypeScript type definitions) on WebStorm IDE 2 answers I am trying to use Webstorm 10's new built-in TypeScript compiler. When compiling a simple Node.js file such as below, it gives a TS compilation error of "Error:(1,...

Trying to implement an object-oriented design model for a simple navbar using TypeScript


javascript,jquery,typescript
Greetings fellow Earthicans, The following code is used on my website: brianjenkins94.me in order to handle baseline navigation functionality and while it was working previously I decided to leverage the class-based approach provided by the TypeScript Language in order to structure my code in a more readable fashion. In doing...

Test if an object conforms to an interface in TypeScript


testing,typescript
If I have a plain-old JavaScript object and a TypeScript interface, how can I write a test that asserts object conforming to my interface? interface Person { name: string age?: number } describe('Person interface check', () => { it ('should conform to "Person" interface', () => { let obj1 =...

resharper is not ignoring tests marked with Category Attribute in XUnit


resharper,xunit.net
having: [Category("Contract")] public class ProgramClientShould { } or: [Trait("Contract", null)] public class ProgramClientShould { } and Resharper -> Options -> Tools -> Unit Testing: "Skip tests from categories" with value "Contract" Still, tests in ProgramClientShould are executed. What's wrong?...

Firebug does not display my JavaScript files


typescript,firebug
I am building a web application with AngularJS en typescript in VS2012. These TypeScript files are all compiled into JavaScript files and send to the client using Bundles (all options turned off, thus I'm sending all files individually). In Firebug HTML view I can see all my JavaScript files, but...

TypeScript does not detect union type with an && operator


typescript
In the below example x is actually a union type of 'boolean | string' but TypeScript considers it a string. Is this a bug or am I missing something? var x:string = false && "foo"; ...

Namespace keyword in TypeScript


c#,namespaces,typescript,keyword
Trying to find out what does namespace keyword mean in TypeScript? Here's some reshuffle they've done recently to use namespace instead of module: https://github.com/Microsoft/TypeScript/commit/224e7630ea17c4547e97f85634f446b877955a67 In the absence of namespace spec, it looks like a rather pointless rename to make the language look C#-like. Or is there an obscure little difference...

How to expose TypeScript modules in NodeJS?


javascript,node.js,typescript
I have a library that I'm building in TypeScript. I'd like to include this library in both TypeScript and JavaScript Node projects. What is the general strategy to do this? Should I compile and have two versions or is there some other strategy I should be using?

Angular with Typescript: HTTP Injector Factory vs. Service


angularjs,typescript,angular-http-interceptors
I have created a Typescript Class (see code...) that I want to use as an HTTP injector. It is being added to the Angular module as a service (not a factory). I have noticed a few issues. When the class defines the 'request' and 'response' functions with capital letters, the...

Node.d.ts issues errors using typescript compiler, how do I fix?


node.js,visual-studio,typescript,jasmine,protractor
I have a project that's a NODE console application project using Visual Studio 2013. When I compile the solution I'm getting typescript errors as follows: Typescript wants a semicolon after export interface ReadableStream extends EventEmitter { readable: boolean; read(size?: number): string|Buffer; //Like this ----> read(size?: number): string;|Buffer; Which means I...

Mocking Angular $window in unit test cases


javascript,angularjs,unit-testing,typescript,jasmine
I have been trying to unit test my angular custom service written in Typescript. The service reads a global variable defined on the Window object. I have made it promise, so that in future I can make a AJAX call to get this information. Here is my stripped down service:...

When Using Typescript+angularjs the api result is not displaying in html


angularjs,typescript
Below are my controller and html: When my make api call in controller i am storing the result in result variable, Now,that result variable when i am trying to print in html it is not printing anything, i have used one more variable name in controller that is printing in...

C# Rest API returns string with double quotes


angularjs,rest,typescript,umbraco7
I have this silly problem, which I hope someone could help me enlighten. I am building an extension for Umbraco7's backoffice, for that I need to receive a simple string. My problem is the string return from the REST api contain double quotes and then AngularJS wont model bind. Here's...

TypeScript project organization, compile into a single JS file?


javascript,oop,typescript
Recently I started working with TypeScript, using WebStorm IDE. Coming from a strong AS3 background I found TS a really good way to write JS, most of the concepts feel really familiar and convenient, but, when it comes to splitting classes,modules into separate files things starting to get really confusing....

Typescript file exporting interfaces comes up 404 using JSPM


typescript,typescript1.5,jspm,systemjs
I'm using Typescript 1.5. I started using jspm. I have a few files that just consist of interface exports. In my tsconfig the module is set to 'system'. It seems to not like files that are just exporting interfaces. It's giving me 404 errors, looking for them in the dist/app...

What is the correct tasks.json config for compiling typescript in Visual Studio Code?


typescript,vscode
Using Ctrl+Shift+B I added a default tasks.json file and uncommented the second task runner block. I have a typescript file in the root of the directory and a tsconfig.json. Everytime I compile I get 'error TS5023: Unknown compiler option 'p'. What is the correct definition to allow me to compile...

Exception with type definition for random-string module


node.js,module,typescript
I am trying to write a .d.ts for random-string. I have this code: declare module "random-string" { export function randomString(opts?: Object): string; } I am able to import the module no problem then with: import randomString = require('random-string'); and invoke: console.log(randomString); // --> [Function: randomString] However, this doesn't work with...

Visual Studio 2015 RC + RequireJS + jQuery


jquery,requirejs,typescript,visual-studio-cordova
I'm using Visual Studio 2015RC + Cordova CLI 5.1.1 + TypeScript + RequireJS + jQuery . I'd like to change the location of my jquery.js file from the scripts folder to scripts/lib. I added a requirejs.config and changed the jQuery location. requirejs.config({ baseUrl: 'scripts/lib', paths: { jquery: 'jquery' } });...

How to compile TypeScript without using any references whatsoever


javascript,angularjs,typescript,tsd
Forgive me if I misunderstand, but I thought that if I used a tsconfig.json file at my project root, then I would no longer need to use any ///<reference path="..." /> tags in order to make my code compile. Am I wrong? For example, I'm using AngularJS. My App.ts file...

How to load System.js modules with TypeScript?


javascript,typescript,aurelia,systemjs
I'm trying to get TypeScript working with the default Aurelia skeleton, which is based on System.JS as a loader. I'm having trouble getting TypeScript to accept module imports. I renamed one of the skeleton files, "nav-bar.js" to "nav-bar.ts" to see if I could convert the example into TypeScript. The code...

Inject dependency to the angularjs directive using typescript


angularjs,angularjs-directive,typescript
Lets say I have a simple angular directive that looks like this: app.directive('setFocus', ['$timeout', function($timeout) { return { restrict: 'AC', link: function(_scope, _element) { $timeout(function() { _element[0].focus(); }, 0); } }; }]); How can I write this using Typescript and get the $timeout accesible within the link function? My example...

TypeScript: Lambdas and using 'this'


lambda,typescript,this
JavaScript frameworks often call callbacks using apply(). TypeScript's arrow notation, however, doesn't seem to allow me to access the 'this' pointer. How's it done? If it isn't, is there a place to down-vote the current 'this' handling on Lambdas?...

How to stop visual studio generate typescript js and js.map files while publishing


visual-studio-2013,configuration,typescript,publishing
I set up my project that combine javascript output into file to $(ProjectDir)dist\output.js and uncheck generate source maps. Tools -> Options -> Text Editor -> Typescript -> Project -> Automatically compile Typescript files which are not part of a project is unchecked as well. While building and running project from...

TypeScript 1.5 doesn't produce output


typescript
Using typescript 1.5 beta. I have the following problem: if there are errors (from typescript point of view) in .ts files, the output .js files aren't produced and previous output (if any) is erased. Is it a 1.5 beta limitation or didn't I understand the right way the phrase from...

Module '“angular2/angular2”' has no exported member 'For'


angularjs,typescript,angular2,typescript1.5
hi I am following the tutorial on the official Angular2 website. https://angular.io/docs/js/latest/guide/displaying-data.html Here is my ts file /// <reference path="typings/angular2/angular2.d.ts" /> import {Component, View, bootstrap, For} from 'angular2/angular2'; @Component({ selector: 'display' }) @View({ template: '<p>name: {{myName}}</p>' + '<p>Friends:</p>' + '<ul>'+ '<li *for="#name of names">'+ '{{name}}'+ '<li>'+ '<ul>', directives: [For] })...

Nuget-deployed C# files excluded from Resharper analysis


c#,nuget,resharper
I'm having trouble understanding a behaviour of Nuget. I've created a basic package that deploys a single Test.cs file into an "HtmlHelpers" folder in a project. I'm following the "convention based working directory" method described on the Nuget site. The issue I'm having is Resharper file analysis isn't enabled for...

Mismatched anonymous define() in Chrome extension content script


google-chrome-extension,requirejs,typescript
I'm trying to build a Chrome extension with TypeScript. The setup is quite simple: In manifest.json { "permissions": [ "webRequest", "webRequestBlocking", "tabs", "storage", "http://*/", "https://*/*" ], "content_scripts": [ { "matches": [ "http://*/*", "https://*/*" ], "js": [ "scripts/require.js", "scripts/require-cs.js", "scripts/main.js", "scripts/contentscript.js" ], "run_at": "document_end", "all_frames": true }], } In model.ts: export...

is it possible to use TypeScript and Babel together


javascript,typescript,babeljs
I am new to both TypeScript and Babel. I have researched both and found they have features the other does not have. I'd like get the best of both world by using TypeScript to organize my code then use babels ES6 features like asyc/await and others. Is this possible.

How do I access the service provider when registering using typescript class


angularjs,configuration,typescript,service-provider,typescript1.5
The following service provider registers successfully. Other controllers can use the service without trouble. My question is how to access the provider in order to configure it before the service is instantiated by the $injector service? module apiService{ export interface IBaseService{ leagueID: number; } export interface IApiBaseServiceProvider extends ng.IServiceProvider{ setLeagueID(leagueID:...

How to do dynamic objects in TypeScript


typescript
Is there any way to define a dynamic object type in TypeScript? In the following example, I would like to define a type for "My Complex Type" by saying: Objects of type "My Complex Type" are objects having "any number of properties" but the values of those properties must be...

Sublime 3 JS Snippets to Typescript


javascript,typescript,sublimetext3,code-snippets
I have a lot of useful snippets on JS. Like cl for console.log(); or fn for function methodName (arguments) { // body... } However I can't use them on *.ts files. How can manage the snippets and complation for js to ts also. Thanks...

Use TypeScript lib.core.d.ts instead of lib.d.ts


javascript,node.js,typescript,typescript1.4
It seems the TypeScript compiler always includes lib.d.ts or lib.es6.d.ts (depending on the compiler target). In our application we have a WebSocket class that is already defined in lib.d.ts. We're running our application under Node.js and not in a web browser, so we actually don't need all of the definitions...

How to detect overflow HTML elements


javascript,jquery,html,css,typescript
I have created a navigation bar with div(s) within it. When i zoom-in, I hide the div's moving out of navigation bar through css [overflow:hidden]. My goal is to create a java-script variable which will tell me what all div's are out of navigation Bar( hidden because of overflow), as...

Setting dynamic properties with key from a private collection in TypeScript


typescript
Running this in the http://www.typescriptlang.org/Playground ... interface TestObj { name:String; } class Test { test; private myCollection:TestObj[] = []; private anyCollection:any[] = []; constructor() { var obj:any = {}; var refObj = {name:'prop'}; obj[refObj.name] = "This works!"; var collection:any[] = []; collection.push(refObj); this.test[collection[0].name] = "This works!"; this.myCollection.push(refObj); obj[this.anyCollection[0].name] = "This...

How to run nunit tests with asp.net 5 projects, espically with ReSharper?


nunit,resharper,asp.net-5
I am developing an asp.net 5 application targeting dnx451. The asp.net 5 project relies some libraries with unit-tests written for nunit 2.x. So the reasonable choice for me is to use nunit for testing the asp.net 5 project. When I running the unit test in ReSharper , the ReSharper says...

What is the type of an object literal key as defined in TypeScript?


javascript,enums,typescript,webstorm,object-literal
I'm not using TypeScript as the primary language for this application, but as the type-hinting assist for JetBrains' WebStorm alongside JSDocs. I'm also using the keyMirror utility to create quasi-enum object literals. Given the following: //enums.js var keyMirror = require('keyMirror'); module.exports = { CRUDVerbs: keyMirror({ //keymirror mirrors the key to...

Typescript - is there a way to specify a global reference?


javascript,node.js,typescript
I'm developing a node.js script using typescript and in order to tsc not to complain about non-browser-js code like require or module.exports, I have to include /// <reference path="lib/node.d.ts" /> in every file. To make things worse, the location to that file needs to be relative to the code file,...

Pros & Cons of using requirejs (-m amd) for typescript+angular projects


javascript,angularjs,typescript,require,amd
For an angular 1.x project that uses typescript, what are the Pros and Cons of using AMD? Meaning, running tsc with the params -m amd and using requirejs, versus simply using the /// <reference path="..." /> for internal modules as well and wrapping in module(s). Which- Makes more sense for...

Extending an interface from a third party definition file


typescript,sequelize.js
I'm using this definition file in my Typescript code. The problem is that, according to Sequelize documentation to set the length of a string column, I should define its type as: Sequelize.STRING(20) and the current definition file doesn't allow this. It allows only Sequelize.STRING (which makes a default column length...

How can this be undefined in the constructor of an Angular config class?


angularjs,constructor,typescript,undefined,this
I've found some examples online, where people create TypeScript config classes and pass them on to Angular. When I've tried it, I got the weird exception, that this was undefined. A closer look to the other implementations revealed, they only use the constructor, so, are those examples actually inherently wrong...

How to declare knockout component in typescript?


javascript,knockout.js,typescript
I am trying to follow example to create a component in knockout. http://knockoutjs.com/documentation/component-overview.html But I have to write a code in typescript. So how can I register component in knockout using typescript? What should I write in .ts file to convert it in something-like below. ko.components.register('like-widget', { viewModel: function(params) {...

How to implement custom sort for koGrid?


javascript,sorting,knockout.js,typescript,kogrid
Data: 16.00 hours 19.99 hours 210.46 hours 262.54 hours 303.19 hours 55.95 hours 60.07 hours 64.07 hours 7.95 hours What I want: I need to allow sorting for this king of data in koGrid (default feature by clicking grid header, asc or desc sort). Problem: The data is string so...

Angular 2/Typescript: require not found


typescript,gulp,angular2
I am trying to get the angular 2 example running with a gulp typescript compiler. The gulp-script compiles import {Component, View, bootstrap} from 'angular2/angular2'; to var angular2_1 = require("angular2/angular2") which does not run in the browser. What is wrong with this? As far as I know, this kind of implementation...

I cannot debug two projects at once - one with Resharper NUnit tests


debugging,visual-studio-2013,nunit,resharper
My team has a solution with multiple projects. One of these projects is an ASP.NET MVC website. Another project contains NUnit tests. We launch these NUnit tests inside Visual Studio 2013 with Resharper 8.2.2. Another developer on my team is able debug both the MVC project and the NUnit tests...