Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Half a day mastering TypeScript feels like writing Java


May 31, 2021 Article blog


Table of contents


The article comes from the public number: Little Sister Taste

It's so much fun to have so many cool things on the front end. H owever, JavaScript is a landblock, especially when you're familiar with a strong type check language like Java, and every time you see JavaScript, you're uncomfortable. A s a backend, writing JavaScript really has a feeling of spitting. Fortunately, there are better options now.

Why learn TypeScript? B ecause its syntax is really like Java. With this, you can get rid of annoying JavaScript and embrace the front-end technology stack.

TypeScript is a superset of JavaScript T his ts that js can be written directly in js I n my first feeling, js is like a compiled executable, and ts is like Java, or Scala, and so on. However, this is only an analogy, many of the syntax in ts, in fact, most of which is used during the compilation period, in the real js file, erased a lot of information.

 Half a day mastering TypeScript feels like writing Java1

As shown above, the ts file generates a normal js file through the tsc compiler. Next, you can execute this normal js file using the node command.

Here's a simple ts code. Doesn't it look like Java?

class Animal {
    public name;
    protected a;
    private b: string;
    constructor(name) {
        this.name = name;
    }
    sayhi() {
        return `my name is ${this.name}`;
    }
}
class Cat extends Animal {
    constructor(name) {
        super(name)
    }
    sayhi() {
        return "meow " + super.sayhi()
    }
    static iaAnimal(a) {
        return a instanceof Animal;
    }
}
function gen<T extends Animal>(name: T): void {
    console.log(name.name)
}

Here's a brief introduction to some basic syntax, of course, some syntax is ES6, but I also rub it together.

Type-related

Because js is a weak-type language with many run-time conversions and cannot use strong type conversions like Java, typescript can enhance some type checking capabilities through language features during the compilation phase. At runtime, most don't have that judgment at all, so ts is more of a process tool.

For a language, basic data types and custom types must be inseparable. ts provides a range of keywords as a special type code, and the others are good to say, and the only thing that interests me a little bit is 联合类型 which is a very interesting feature.

  • typeof keyword is used to determine if it is a type
  • string indicates that it is a string type, which is different from Java and has a lowercase initial
  • boolean and Boolean types are different
  • number directly represents the number type, without so many troublesome precision problems (0b, 0O, 0x indicate progress issues)
  • any is a universal type, equivalent to Object in Java, all any equivalent to ordinary js. So, if you hate ts, you can go all the way to heaven
  • never represents value types that never exist
  • object a non-original type, unlike in Java
  • string | number is a union type like this, which is also a very magical point. Only these two types of transformations are allowed here, and methods can be called to take the intersection of the two
  • ` 之间的字符串可以使用类似shell的语法,做模版 ${}`
  • readonly This is actually a keyword that indicates a read-only property
  • [propName: string]: any; This line of code is worth studying, but is not recommended
  • number[] array is similar to Java, but this is the syntax after the declaration, and the value is declared by the value, not by the
  • There is no difference between a function function and javascript, there are two ways to declare it. Lambda must be a strong point for js
  • => Grammar is also more disgusting, and ES6 together can write a big article
  • ...rest pay attention to this thing! Similar to the meaning of variable parameters in Java
  • as is a keyword that we can understand as Java cast but it is also just a syntax check that runs out of control. (window as any) is cool, but error-prone

The declaration is relevant

  • let is used to declare common variables with a small scope, within
  • var scope is large, function-level, or global
  • const read-only variables are static; readonly is dynamic, but cannot be changed after declaration
  • declare var declares the global variable (file of .d.ts suffix, which is a convention)
  • declare function declares the global method
  • declare class global class
  • declare enum global enum enum type
  • declare namespace global namespace
  • export This is mainly used for npm, and subsequently can be imported using import

So what's declare? Privately thought that this is similar to __init__.py file in python, used to expose some interfaces and functions, and provided basic data for code autocomplete.

Two default conventions. W ith tsconfig.json configured, the tsc command can be compiled directly. /// Three slash instructions, very ugly.

About Class

Students from Java will find that these concepts are similar to Java, but the syntax of ts is simpler.

  • get set is actually a keyword, and you can keep up with the function directly. You can change the assignment and read behavior of properties!
  • static instanceof public protected private these are also there, really feel and write Java is no different
  • constructor defaults to a construction method, unlike Java and class nouns
  • abstract also has, indicating that subclasses must be implemented, no different
  • Regarding the difference between class and interface, I think familiar with java is transparent to ts
  • In Java, syntax is also very perverted because you often don't know where to put <> I n ts, it's just as hard. Specific how familiar, only in practice honed

About type, interface, class

  • interface defines the interface, where the interface is interesting and can declare entities, but all values must be assigned. Y ou can do this by adding ? before the member variable w ay to show that it is not necessary, but very ugly; ? You can also define the optional parameters of the function, 6 very
  • type like interface, is erased at compile time. There are nuances in the syntax of the two, and type can define more types, such as basic types, union types, tuples, and so on
  • class can implement methods in it, a bit of Java taste, so it won't be erased by the compiler. Javascript uses constructors to simulate class.

Develop tools

tsc is the compiler for typescript. If the compilation goes wrong, you can specify the underlying syntax characteristics.

tsc --target es6

It is recommended that it be configured in the tsconfig.json file and will be automatically identified.

{
    "compilerOptions": {
        "module": "commonjs",
        "outDir": "lib",
        "declaration": true,
        "target":"es6"
    }
}

vscode, via .d.ts file, can do automatic complement and syntax checking. But for complex, personalized configurations, smart tips and configurations like ideas are still not possible.

As a result, you must have a reference document on hand and be familiar with the catalog and functionality of the reference document. W hen you encounter the appropriate configuration parameters, you have to go through the appropriate places and copy them over. This is too painful for a javar.

Above is W3Cschool编程狮 about half-day mastering TypeScript, feels like writing about Java, I hope to help you.