Learn the typeScript premise
Knowing the pros and cons of typeScript will help you know if you need to learn typeScript
Advantages:
- Avoid type exceptions that may occur in the development process, improve the efficiency of code execution and the reliability of code,
- Support automatic conversion of NEW ES6 features, minimum compilation to ES3
- Any javaScript runtime environment (browser, desktop server Node) can be converted
- The ecology is particularly sound and perfect. Our front-end use of vscode has a lot of type tips, especially smooth use, improve development efficiency
- Belong to “progressive”, do not have to learn all the knowledge of TS, learn to use one, can be compatible with JS code, reduce the threshold of use
Disadvantages:
- Js is not flexible and free
- More concepts (such as interfaces, generics, enumerations)
- TypeScript adds costs in the early stages of shorter or smaller projects, with lots of type and interface declarations (although these costs are not a permanent problem if you are maintaining large projects for a long time).
If you feel like you’re working on large page systems for a long time and want to use the newer features of es6+, vscode has better tips for improving your development efficiency, then learning TypeScript is a good place to start. The cost of learning inflexibility and extra concepts, upfront type and interface declaration time costs are relatively insignificant. And you can use them gradually, you don’t have to learn them all, you can use them. Fully compatible with many platform JS runtime environments.
The original type
The primitive type declares the first letter to be lowercase
// Primitive types can default to null strictly mode disallowed
const a: number = 6 // NaN Infinity
const a1: string = 'hello typescript'
const a2: boolean = true // false
const a3: undefined = undefined
const a4: null = null
const a5: void = undefined // The strict mode can only be undefined or null
// If target is set to ES5, new content added on es6 will display an error
const a6: symbol = Symbol('millet')
const a7: void = undefined
Copy the code
Chinese error message
// yarn tsc –locale zh-CN
Vs Code can also configure the search for typescript locale to change to zh-cnThe error message will become Chinese
Scope problem
Modularize ts declaration variables
- You can put code in a function that executes immediately
void function() {}()
- You can use export so that all variables are in this module
export{}
You may not even notice it at work, but what is it
The Object type
If the variable is defined as object, it can be function [] {}
-
Object, which stands for a type other than the original type, object {}, function array []
-
We can also define an object that has a fixed field attribute, and an error will be reported if the attribute is exceeded or if the attribute name is not in the declaration. Object declarations can be {name: string,age: number} but interface is recommended
// An error is reported with an additional attribute
const person: {name: string.age: number} = {name: 'ali'.age: 20}
// Interface declarations are preferred
interface IPerson {
name: string.age:number
}
const person: IPerson = {name: 'ali'.age: 20}
Copy the code
An array type
There are two ways to define it:
- Array
- number[]
// Let’s look at the benefits of strong typing
function sum(. args) {
// Check if each member is a number
return args.reduce((prev, current) = > prev + current,0)}function sum(. args:number[]) {
// If you don't know what to do
return args.reduce((prev, current) = > prev + current,0)}Copy the code
// If it’s JavaScript, we need to check whether each element in the array is a number or not. If the parameter has a type declaration, we don’t need to check
A tuple type
This is a type that defines an array of fixed length and the type of each element is fixed
const tuple: [string, number] = ['zlx'.100]
// const age = tuple[0]
// const name = tuple[1]
const [age, name] = tuple
// ---------------
// React uses useState as a tuple
// And object. entries({foo: 'bar'})
Copy the code
Enumerated type
There are several fixed value using the enumeration more semantic Used above all make a two-way enumerable object Can use index access State can also be used for index values If index is generally not applicable for state is worth words suggest using constant enumeration in front of the statement and const TSC can be compiled code will change / / second String type
// The second string
enum PostStatus2 {
Draft = 'aaa',
Unpublished = 'bbb',
Published = 'rrr',}const post = {
title: 'Hello TypeScript'.content: 'TypeScript is a typed superset of javascript'.status: PostStatus2.Draft,
}
You can use the index to access the state, or you can use the state to obtain the index value. If you do not use the index to obtain the state, it is recommended to use constant enumeration before the declaration of const
// TSC compiles the code and changes it
const enum PostStatus3 {
Draft,
Unpublished,
Published,
}
const post1 = {
title: 'Hello TypeScript'.content: 'TypeScript is a typed superset of javascript'.status: PostStatus3.Draft,
}
// After compiling
var PostStatus2;
(function (PostStatus2) {
PostStatus2["Draft"] = "aaa";
PostStatus2["Unpublished"] = "bbb";
PostStatus2["Published"] = "rrr";
})(PostStatus2 || (PostStatus2 = {}));
var post = {
title: 'Hello TypeScript'.content: 'TypeScript is a typed superset of javascript'.status: PostStatus2.Draft,
};
var post1 = {
title: 'Hello TypeScript'.content: 'TypeScript is a typed superset of javascript'.status: 0 /* Draft */};Copy the code
Function types
- Controls the input and output data types of functions
- Optional arguments and those with default values must be written at the end of the argument list. This reason is also very simple, JS parameters are passed through the location of the transfer, if it is the default and optional parameters can not be passed, do not pass the default will help you make up, optional parameters do not pass also does not affect the right and wrong.
- If you pass arbitrary arguments you can use the residual argument expression
. rest
Any type
No type checking is done for any parameters or variables, and no errors are reported for any values.
It is best not to use this type, otherwise the TS type system is meaningless, but we should not use this type when we are compatible with older code
Type Inference
If you do not annotate the identifier, TS will deduce the value type for your use. This feature is implicit type inference. (User does not perceive)
It is recommended to add an explicit type to each variable, which makes it easier to derive the type and reduce code execution errors.
Type Assertions
In special cases where typeScript can’t infer the specific type of a variable, we force a variable type to be specified. The type of a variable is specified at compile time, not run time. There are two types of conversion that can make type assertions at run time
- You can use the AS key value
const nums = [110.120.119.112]
const res = nums.find(i= > i > 0)
const num1 = res as number // We can tell the TS compiler that the value of this variable must be number
Copy the code
- Assertion with <> // cannot be used under JSX
Interfaces
We can think of it as a norm a contract. Is an abstract concept used to define the structure of an object. The use of this interface is subject to all the specifications of the interface
So it’s kind of intuitive to say, what kind of members should there be in an object and you can say what kind of members should there be semicolons
interface IPost {
title: string;
content: string;
}
function printPost(post: IPost) {
console.log(post.title)
console.log(post.content)
}
printPost({
title: 'Hello TypeScript'.content: 'A javascript superset'
})
Copy the code
Define optional, read-only members
Optional members: members followed by a question mark Read-only members: use the keyword readonly before variables
interface Post {
title: string;
content: string; subTitle? :string; // This parameter is optional
readonly summary: string;
}
Copy the code
Classes (Classes)
Describes the abstract characteristics of a specific class of transactions
Cell phones, for example, are one type
An abstract member that describes a class of concrete objects
Before ES6, function + prototype simulated implementation classes, ES6 began to have specialized classes in JavaScript
TypeScript enhances class syntax
- Be sure to specify a class member in a class using a colon to define the member type or assign an initial value
class Person {
// name: string; // init name
// Type initialization can be defined
age: number;
// Assignment can also be initialized
name = 'Meituan'
constructor(name: string, age: number) {
this.name = name;
this.age = age; }}Copy the code
- Access modifier
- Class access modifiers are public by default and can be accessed externally. We recommend adding them to make the code easier to understand
- External access to the variable will fail if the property is set to private
- Protected is a protected property and is only accessible in subclasses
class Person {
// name: string; // init name
// Type initialization can be defined
// With private, an error is reported when external access is made
private age: number;
// Assignment can also be initialized
public name = 'Meituan'
constructor(name: string, age: number) {
this.name = name;
this.age = age; }}Copy the code
Constructors can also have access modifiers. When constructors are private, no external powers are allowed to create the class. However, we can use the static method create to define new powers object.create ()
class Student extends Person {
// The private modifier constructor cannot be created outside the class
private constructor(name: string, age: number) {
super(name, age);
console.log(this.gender);
this.gender = false;
}
// This can be done using static methods of the class
static create(name: string, age: number) {
return new Student(name, age)
}
}
const tom = new Person('Google'.18)
console.log(tom.name)
// console.log(tom.age)
// console.log(tom.gender)
// Cannot create student object with new
// const jack = new Student()
const jack = Student.create('jack'.20)
Copy the code
The read-only nature of the class
Readonly Sets a property to read-only and must be used after the access modifier
class Person {
protected readonly gender: boolean
}
Copy the code
interface
Mobile phones are one type, but all mobile phones in the market can make calls and send text messages, because these are the characteristics of mobile phones. In the old days, landline phones also had the ability to make calls. There are also common characteristics between different classes. These characteristics can then be abstracted as interfaces
interface Eat {
eat(food: string) :void
}
interface Run {
eat(distance: string) :void
}
class Person implements Eat.Run {
eat(food: string) :void {
console.log('Eat gracefully:${food}`)
}
run (distance: string) :void {
console.log('Walking upright:${distance}`)}}class Animal implements Eat.Run {
eat(food: string) :void {
console.log('Oink oink eat:${food}`)
}
run (distance: string) :void {
console.log(Crawl ` :${distance}`)}}Copy the code
Object-oriented languages like Java and c# suggest that interfaces should be much simpler, with one interface having only one capability
We need to learn how to use interfaces to abstract some capabilities from classes. So see here if you know the Java c# words can better abstract interface, so it is best not to limit yourself, must be more open their technical career, learning its specific language, so that their knowledge more systematic more comprehensive. People who only know javascript can’t design great products even if they’re good at it. For example, the frameworks that are popular today are the ones that MVVM first appeared in other languages
An abstract class
Abstract class is similar to interface, but different from interface, abstract class contains some concrete implementation, that is generally large class we will use abstract class implementation, such as the animal is generally a general reference, there is no concrete representation, we can use abstract class implementation
Abstract class or to have a good understanding of his ideas, and continue to be familiar with the use of there is no great difficulty
The generic
When we use a function interface or class, we don’t specify the related type. We wait to specify the specific characteristics when we use them. The goal is to maximize the reuse of our code
Simply put, when defining a function we cannot program an argument with an explicit type. Let’s pass another type parameter when we use it
function createArray<T> (length: number, value: T) :T {
const arr = Array<T>(length).fill(value)
return arr
}
const res = createArray<string>(3.'foo')
Copy the code
Type declaration
We will use NPM installed third-party modules that are not developed in typescript, so the object members provided by NPM will not have a strong typing experience.
In lodash, for example, if we use a function, when we use vscode that function doesn’t have a good input parameter type hint or output content type hint. Ts can be optimized using the syntax of type declarations
import {camelCase} from 'lodash'
declare function camelCase(input: string) :string
const res = camelCase('hello typed')
Copy the code
In order to be compatible with modules that are not developed by TS, the TS community is very powerful. Now many common NPM modules help to write the corresponding type declaration, we just need to install the corresponding NPM module declaration
Conclusion: Hope to be helpful to readers…