I’m sure many teams have encountered this situation, where the implementation of TS does not have a positive effect, but increases the development cost (after all, writing any is three characters, and there are a lot of other aspects of the implementation of TS). So why do we use TS? Why write so much ‘any’ after you use it?

Typescript is always used as “anyscript”?

There are a lot of “any” in many development projects, and sometimes developers use a lot of “any” for convenience. After all, defining a type is much more difficult than writing an any. Then I did a search in the project and 436 Any’s came up. If the penalty is 100 times, this project has punished me 4.36 times.

How to solve this phenomenon?

In order to solve this problem I also specially went to Baidu, want to seek the answer, and then I opened Baidu

You must tie the bell

I found that there were many questions but not many answers, so I found an unremarkable answer in a corner of the boundless answers, which had not been praised by others.

Who wrote it? Who doesn’t? Go ahead, I look around the room and shout, where’s the knife? Who wrote “any”? Who did I chop? At this time I heard a weak voice, brother, I looked at the git submission record, it shows that you wrote… Let’s talk about why it’s best not to use any, and why we need to define a type.

Why should I define a type?

The first thing we need to understand is why we define a type, what does it do?

TypeScript has become standard on large projects, providing a static typing system that makes code more readable and maintainable. At the same time, it provides the latest and ever-evolving JavaScript features that allow us to build more robust components.

Jkchao. Making. IO/typescript -…

The first is for code completion

So first we define num as number and then we get some methods on number and we complete them.

The second is type checking

Type checking is critical. For example, if we assign a string to a number, we get an error.

Increased code readability and maintainability

The type system is actually the best documentation. Most functions can be found at compile time by looking at the type definition. This is better than making errors at run time, which enhances the functionality of the editor and IDE. Including code completion, interface prompt, jump to define, refactoring, etc For example, we presents a framework delon ali, sometimes don’t need to see the document, jump straight definition, in order to prevent your wayward, do a limit on the type, this in before I dare not even think about, meet some of the third party will not pass, or to check the document, Or read the source code, is very affect efficiency.

The mouse goes up to have a hint directly

Jump directly to the definition, each value meaning, constraints are clearSo since this thing is so good, how do we write this thing and how do we use it?

Great trees are good for nothing but shade

Newton succeeded because he stood on the shoulders of giants. We are at best sitting under a tree, and we do not have a type definition file when we reference a third party NPM package other than TS in the project. We can solve the problem of introducing non-TS third-party projects by downloading a library of definition files written by third parties through NPM. DefinitelyTyped is undoubtedly one of TypeScript’s greatest strengths, the community has documented 90% of the top JavaScript libraries.

You can install @types via NPM, such as adding a declaration file for jquery:

npm install @types/jquery --save-dev

Jkchao. Making. IO/typescript -…

Do it yourself

Of course, other things are good, or you have to make your own food and clothing. So how do we write a declaration file.

Javascript data types

  • Primitive data type
  • Object

MDN document address

let isDone: boolean = false let age: number = 10 // string let firstName: string = 'ddking' let message: string = `Hello, ${firstName}, age is ${age}` // undefined null let u: undefined = undefined let n: Null = null // Note that undefined and null are subtypes of all types. Let num: number = undefined // any let notSure: any = 4 notSure = 'maybe it is a string' notSure = 'boolean' notSure.myName notSure.getName()Copy the code

So what are primitive data types? The DOCUMENTATION for MDN makes it clear that all types except Object are immutable (the value itself cannot be changed). We call these types of values “raw values.”

Array and a Tuple

After talking about the primitive data type, the Object type, the first thing to contact is the array, which should be a kind of data structure that we front-end development engineers are most familiar with. There are many ways to define it. Here we will introduce the simplest one. Ok, coming to the code:

// The simplest way is to use "type + square brackets" to represent arrays: Number [] = [1, 2, 3, 4] number[] = [1, 2, 3, 4]  arrOfNumbers.push(3) arrOfNumbers.push('abc')Copy the code

function

Functions are an important part of a program

So the function is mainly composed of two parts, one is the input, which is usually realized by passing different parameters, and the second is the output, which is the return result of the function.

Function add(x: number, y: number): number {return x + y} let result = add(2, 3) function add(x: number, y: number): number {return x + y} let result = add(3) So how do we implement optional arguments? Function add(x: number, y: number, z? : number): number { if (typeof z === 'number') { return x + y + z } else { return x + y } }Copy the code

Interface: the interface

Interfaces make it very easy to define the type of an object. This concept is called an interface. Interfaces in typescript are very flexible. The shape of the object is described, which is also the easiest to understand. Interface itself is like an abstract contract or drawing. It is very flexible and can describe various types of programming languages

interface Person { name: string; age: number; } // We then define a variable ddking of type Person. In this way, we constrain the shape of DDking to be the same as the interface Person. let ddking: Person ={ name: 'ddking', age: 20 }Copy the code
Optional attribute
interface Person { name: string; age? : number; } let ddking: Person = { name: 'ddking' };Copy the code
Read-only property
interface Person { readonly id: number; name: string; age? : number; [propName: string]: any; } ddking.id = 9527;Copy the code
Interface description function
interface ISum {
  (x: number, y: number) : number
}

Copy the code

Use of generics and their implementation

To understand patterns, think about how they came to be.

The motivation of the paradigm

As above picture we incoming and return don’t do unified at this time we found a problem, we introduced to the string, but returned to any, we lost the types of variables, it’s not a good phenomenon, but we the incoming type is various, what all can, string, number, Boolean, or even complex type. This way the incoming and return can not be consistent, and there may even be a bug

From what we said before, type inference, if you assign a value to a variable, TS can help you guess its type, but when it comes to functions, it can’t guess, and that’s the first reason generics are created, type inference doesn’t flow into functions. But we still want to return the corresponding type depending on the parameter passed in. The whole idea of TS is to get the type, and without the right type, it’s 90 percent less powerful, which is why generics came in the first place

The definition of a paradigm

Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use.

function echo<T>(arg: T): T {
  return arg
}

Copy the code

You can refer to this article, which is easy to understand

Juejin. Cn/post / 688789…

TS Some utility generics use and implementation

Most of these generic interface definitions are synthetical sugar (shorthand), and you can even find them in the typescript package lib.d.ts, most of which is included in the latest version of typescript (2.9)

zhuanlan.zhihu.com/p/40311981