Typescript Is Declared but Its Value Is Never Read String Any

TypeScript can help you with writing less bugs! Each version improves the detection of common errors. However, all the checks are not enabled by default. In this blog mail, we'll meet the different compiler options and the kind of errors they help to catch. There is no specific social club considering all of them are important.

If you're notwithstanding not using TypeScript, y'all tin read my previous mail: Yet not using TypeScript?.

#Invalid arguments, unknown method/belongings, or typo

TypeScript knows what is valid or not every bit it knows the types of the variables, or functions. This prevents typo or using an unknown method or property, or using an argument of type string instead of a number, etc. So, you don't need to execute your code to observe this kind of event.

                      var            author = {            nickname:            "meziantou",            firstname:            "Gérald",            lastname:            "Barré"            };            console.log(author.lastName);            // Error: property 'lastName' does not be on blazon '...'. Did you lot mean 'lastname'?            author.nickname.trimStart();            // Error: property 'trimStart' doest not be on blazon 'string'.            writer.firstname.charCodeAt("1");            // Fault: Statement of type 'string' is not assignable to parameter of blazon 'number'.                  

#Null- and undefined-aware types

I retrieve strictNullChecks is the near important TypeScript compiler flag. This volition help you lot detect lots of potential errors. We often suppose a value is non null or undefined, which is not ever true. The strictNullChecks option considers cypher and undefined equally different types. Then, if a variable can be null, you must explicitly declare it as blazon | nada;

                      {            "compilerOptions"            :            {            "strictNullChecks"            :            truthful            }            }                  
                      function            a(s:              string            ) {            console.log(s.length);            // ok            }            a(null);            // error: null is not assignable to cord            function            b(s:              string              |              null            ) {            panel.log(due south.length);            // fault: s is probably 'null'            }            part            c(s?:              cord            ) {            console.log(southward.length);            // error: south is probably 'undefined'            }        

#Report error when not all code paths in part return a value

The noImplicitReturns compiler option ensures you ever write a return statement in all branches of a method if at least one branch contains a render statement with a value.

                      {            "compilerOptions"            :            {            "noImplicitReturns"            :            true            }            }                  
                      // Error: Not all code paths return a value.            function            noImplicitReturns(a:              number            ) {            if            (a >            x) {            render            a;     }            // No return in this branch            }        

#Report fault on unreachable lawmaking.

The allowUnreachableCode compiler option ensures y'all don't have dead code in a function. It detects unreachable code such as if (constant) or code after returns. Note that in JavaScript, the return statement ends at the end of the line. So, if y'all write the value of the return statement on the next line, the function volition return undefined, and the next line is never executed.

                      {            "compilerOptions"            :            {            "allowUnreachableCode"            :            false            }            }                  
                      function            allowUnreachableCode() {            if            (simulated) {            console.log("Unreachable code");     }            var            a =            1;            if            (a >            0) {            return            ten;            // Unreachable code            }            return            0;            console.log("Unreachable code"); }        

#Report errors on unused locals or unused parameters

The noUnusedLocals and noUnusedParameters compiler options ensure you don't accept unused variables or parameters. This may occur subsequently code refactoring, and just because you forget a part of your algorithm. For the compiler, an unused parameter or variable is a parameter or a variable with no read access.

                      {            "compilerOptions"            :            {            "noUnusedLocals"            :            truthful            ,            "noUnusedParameters"            :            true            }            }                  
                      function            f() {            var            a =            "foo";            // Error: 'a' is declared only its value is never read            return            "bar"; }            function            f(n:              number            ) {     n =            0;            // Never read            }            grade            C            {            private            m:            number;            // this.m is never read            constructor() {            this.g            =            0;     } }        

#Report errors on excess holding for object literals

The suppressExcessPropertyErrors compiler option check your don't take unexpected properties in an object. This may assistance you detecting typo in your code.

                      {            "compilerOptions"            :            {            "suppressExcessPropertyErrors"            :            faux            }            }                  
                      var            x: {            foo:            number            }; 10 = {            foo:            one,            baz:            two            };            // Error, excess property 'baz'            var            y: {            foo:            number, bar?:            number            }; y = {            foo:            1,            baz:            2            };            // Error, excess property 'baz'                  

#Report errors on this expressions with an implied any type

A function's this keyword behaves a little differently in JavaScript compared to other languages. In most cases, the value of this is determined past how a office is called. It can't exist set past assignment during execution, and information technology may be different each time the role is called.

You lot can read more about this in the MDN documentation.

TypeScript can't detect automatically the blazon of this in a role because the value of this depends on the way the function is chosen. In this instance, TypeScript uses the any type and you lot can't cheque usages correctly. You tin forestall this beliefs by forcing the typing of this. Thus, your code volition exist typed, and you'll get all the benefices of that.

                      {            "compilerOptions"            :            {            "noImplicitThis"            :            truthful            }            }                  
                      function            noImplicitThis() {            render            this.length;            // Error: 'this' implicitly has type 'any' because it does not have a blazon annotation            }        

You tin can correct your lawmaking by typing this:

                      function            noImplicitThis(              this:              string[]) {            return            this.length;            // ok            }        

#Report errors for fall through cases in switch statement

Sometimes, you tin can forget the intermission keyword in a switch case. This may lead to undesired behavior. With the noFallthroughCasesInSwitch compiler option, TypeScript detects the missing break and reports an error.

                      {            "compilerOptions"            :            {            "noFallthroughCasesInSwitch"            :            true            }            }                  

#Disable bivariant parameter checking for function types

The strictFunctionTypes compiler option ensures you are using compatible functions (arguments and return types).

                      {            "compilerOptions"            :            {            "strictFunctionTypes"            :            true            }            }                  
                      interface            Animal            {            name:            cord; };            interface            Dog            extends            Creature            {            brood:            string; };            var            f            = (animal: Beast) => animal.name;            var            1000            = (dog: Dog) => dog.brood;  f = chiliad;            // error: g is not uniform with f            // error: Blazon '(canis familiaris: Dog) => any' is not assignable to type '(animal: Animal) => any'.            // Types of parameters 'canis familiaris' and 'creature' are incompatible.            //   Blazon 'Creature' is not assignable to type 'Dog'.            //     Property 'dogProp' is missing in type 'Beast'.                  

The following blog postal service explains in details why those 2 functions are incompatible: https://blogs.msdn.microsoft.com/typescript/2017/10/31/announcing-typescript-ii-half dozen/

          - Is it okay for a value of type (dog: Canis familiaris) => whatsoever to say it tin can be used in place of a (animal: Animal) => whatever?     - Is it okay to say my function simply expects an Animal when it may utilise properties that on Dog?         - Only if an Beast tin exist used in place of a Dog – so is Fauna assignable to Domestic dog?             - No! Information technology's missing dogProp.        

#Written report errors for indexing objects lacking alphabetize signatures

The suppressImplicitAnyIndexErrors pick prevents you from accessing properties using the indexer syntax unless the holding is defined or an indexer is defined.

                      {            "compilerOptions"            :            {            "suppressImplicitAnyIndexErrors"            :            false            }            }                  
                      var            ten = {            a:            0            }; 10["a"] =            1;            // ok            10["b"] =            1;            // Fault, blazon '{ a: number; }' has no index signature.                  

#Parse in strict manner and emit "employ strict" for each source file

The alwaysStrict compiler option indicates the compiler to ever parse the file in strict mode and to generate "use strict";, so you don't have to set information technology in every file. If you don't know what is the strict style, I should read the great post from John Resig: https://johnresig.com/blog/ecmascript-5-strict-style-json-and-more than/

Strict mode helps out in a couple of ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors when relatively "unsafe" deportment are taken (such equally gaining access to the global object).
  • Information technology disables features that are confusing or poorly thought out.
                      {            "compilerOptions"            :            {            "alwaysStrict"            :            true            }            }                  

#Report errors on unused labels

The usage of labels is very uncommon. If you don't know them, information technology's ok. If you are curious, you tin can bound to the documentation. TypeScript provides a compiler choice to ensure you don't have an unused label in your code.

                      {            "compilerOptions"            :            {            "allowUnusedLabels"            :            fake            }            }                  
                      loop1:            for            (let            i =            0; i <            three; i++) {            loop2:            // Error: Unused label.            for            (allow            j =            0; j <            three; j++) {            break            loop1;     } }        

#Written report errors on expressions and declarations with an implied any blazon

When the TypeScript compiler cannot determine the type of an object, it uses any. Therefore, you cannot get the advantages of the type checker. This is non what you want when you utilize TypeScript, so the compiler raises an error. You tin fix this fault by specifying the type.

                      {            "compilerOptions"            :            {            "noImplicitAny"            :            true            }            }                  
                      role            noImplicitAny(args) {            // Error: Parameter 'args' implicitly has an 'whatsoever' type.            console.log(args); }        
                      function            noImplicitAny(args:              cord[]) {            // ok with the type information            console.log(args); }        

#Report errors in *.js files

If you use js files along with ts files, you tin can check them using TypeScript. The compiler will use information from JSDoc, imports, and usages to validate your code. The verification won't be equally powerful as for ts files, but this is a skillful offset. You lot can read more nearly how the compiler handle js files in the wiki: https://github.com/Microsoft/TypeScript/wiki/Type-Checking-JavaScript-Files

                      {            "compilerOptions"            :            {            "allowJs"            :            true            ,            "checkJs"            :            true            }            }                  

#Conclusion

TypeScript has a lot of options to increment the robustness of your lawmaking. By enabling all of them, you'll reduce the number of errors at runtime. And so, you can employ some nice techniques to help yous write even meliorate lawmaking, such equally the pseudo nameof operator.

Do you have a question or a proposition well-nigh this post? Contact me!

pewfivemplarity.blogspot.com

Source: https://www.meziantou.net/detect-common-javascript-errors-with-typescript.htm

0 Response to "Typescript Is Declared but Its Value Is Never Read String Any"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel