preface
Hi, this article is a summary of my learning about TypeScript. The current version only covers the basics of typeScript usage, modules, namespaces, modifiers, and so on, making the case a bit paltry when summarizing. I will summarize and output in the ts project demo later. I studied by watching the combination of teaching videos and TS official documents. In the learning process of the difficult part, I will also check the experience posted by some masters to absorb. The original intention of this article is to hope to deepen their impression, at the same time can learn their own content for a certain output. Of course I as a vegetable chicken summary is not very in place. If you find any problems, please point them out bluntly. I will correct them in time. Thank you for your support. ღ(´ · ᴗ · ‘)
Part 01 – TypeScript
TypeScript
isA programming language developed by Microsoft, it isJavaScript
A superset of.
TypeScript
Extended syntax, so any existing JavaScript program can run inTypeScript
In the environment.TypeScript
Is designed for large application development and can be compiled into JavaScript.
TypeScript
The cost of learning is not as great as imagined. As progressive programming syntax, you can write it directly up frontJavaScript
“, and then add a feature by learning about it.
Part 02 – Installing TypeScript and basic commands
Install the TypeScript
npm i typescrpit --dev
Copy the code
Execute ts file to compile to JS file
tsc .\getingTs.ts
Copy the code
Perform configuration file initialization
tsc -- init
Copy the code
Error message in Chinese
tsc -- locale zh-CN
Copy the code
Part 03 – TypeScript configuration files
Json If a tsconfig.json file exists in a directory, it means that the directory is the root of the TypeScript project. The tsconfig.json file specifies the root file and compile options directory structure to compile this project
---- src/
---- dist/
|---- index.js // Compiled js file
|---- index.ts // The entire tool library entry
|---- tsconfig.json// Config file
Copy the code
Commonly used configuration items — because too much so detailed list only commonly used to view the official document www.tslang.cn/docs/handbo…
{
"compilerOptions": {
"target": "ES5".// The target language version
"lib": [ "es5"."es2015"].// Standard library declaration
"module": "commonjs".// Specify the template standard for generating code
"noImplicitAny": true.// Implicit any types are not allowed
"removeComments": true.// Delete comments
"preserveConstEnums": true.// Keep const and enum declarations
"sourceMap": true // Source code mapping to generate target file sourceMap file
"rootDir": "src".// Entry folder
"rootDirs": ["src"."src/class",].// Set multiple entry folders
"outDir": "dist".// Output folder after compilation
"strictNullChecks": true.// Check if the variable cannot be null
"experimentalDecorators": true Support for decorator features
},
"files": [ // Specify the file to compile
"./src/index.ts"]}Copy the code
Part 04 – TypeScript Basic data types
TypeScript supports almost the same data types as JavaScript, and it also provides useful enumerated types for us to use.
Boolean Indicates the Boolean value type
const doBoolean: boolean = false; // true
Copy the code
Number Number type
The Number types specified in TS are supported in addition to constants, NaN, Infinity, and floating point numbers, including decimal hexadecimal binary and octal literals.
const doNumber: number = 1;
const doNaN: number = NaN;
const doInfinity: number = Infinity;
const doHex: number = 0xf00d
Copy the code
Sring The value is a string
In addition to recognizing normal strings, template strings and concatenated strings can also be used normally and can be defined in combination with other variables.
const doString: string = `foo`;
const testString: string = `foo${doString}and${doNumber + 1}`;
const spliceString: string = 'foo'+doString+'and'+doNumber + 1;
Copy the code
Object Object type
Object is not a generic object type, but refers to all non-primitive types. That is, a type other than number, string, Boolean, symbol, null, or undefined. This means that when an object is defined, all primitive types are not specified.
Error: const foo: object = 123; // Type "number" cannot be assigned to type "object".
Copy the code
And the object type doesn’t just refer to ordinary objects
const foo1: object = function name() {};
const foo2: object = [];
const foo3: object = {};
Copy the code
Of course, you can also define objects in literal form. Note that if you add specified members, you have to make sure that there is a one-to-one correspondence, neither more nor less
const foo4: { a: number; b: string } = { a: 1.b: "1" };
Copy the code
Array Array type
There are two ways to define array method one: you can follow an element type with a [] to indicate an array of elements of that type
const arr1: number[] = [1.2];
const arr2: object[] = [{}, {}];
const arr3: any[] = [{}, function () {}];
Copy the code
Method two: array generics can be used to represent
const arr1: Array<string> = ["a"."b"];
const arr2: Array<object> = {}, {}];const arr3: Array<any> = {},function () {}];
Copy the code
Tuple Type of a tuple
The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type.
const tuple: [number.string] = [18."a"];
Copy the code
However, the type and quantity of the array must be the same as the specified type. Otherwise, an error will be reported.
const tuple: [number.string] = ["Ethen".18];// Error
const tuple: [number.string] = [18."Ethen".'boy'];// Error
Copy the code
Enum Enum type
By default, element numbers are assigned to members starting at 0
enumEnumeration name {member1Members,2. }enumFamily Me} {Mom, Father,// Mom=0 Father=1 Me=2
enum Color { Red, Green,Blue,}
Copy the code
And enumeration values are only readable properties that cannot be changed after definition. Enumeration is a type that can be used as a type annotation for a variable
let c: Color = Color.Green; // c=1
Copy the code
Of course, you can also specify the value of the member manually. Note, however, that if the initialization assignment is of a string type, other members are also assigned accordingly.
enum num {
one = 1,
two , / / 2
three , / / 3
}
Family {
Mom = 'emily',
Father='joe' ,
Me='mark',}Copy the code
And we can find its name by enumeration. For example, if we know that the value is 2, but are not sure which name it maps to, we can look up the corresponding name.
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2]; // Green
Copy the code
Any Any type
Any stands for any type, which means that any type can be specified. At the same time, there is no difference between dynamic types and JS types, which means there are still type hazards. Therefore, the any type is typically used to pass these values through compile-time without requiring the type checker to check them. For example, document.getelement json.stringfy
const flag: any = 'string'; //number undefined ....
Copy the code
Void Void type
Void void indicates that there is no type and is usually used to specify a function that has no return value. It usually doesn’t make any sense because you can only assign null and undefined (if not null, you can only assign undefined)
function void() :void {
console.log("no return");
}
const noTarget: void = undefined;
Copy the code
Never type
The never type literally represents the types of values that never exist.
When you throw an exception inside a function, the function Never returns a value, so it is defined as type Never
function error(message: string) :never {
throw new Error(message);
}
Copy the code
Part 05 – TypeScript type features
TypeScript has many types in addition to these types.
Type inference
In TypeScript, type inference helps you specify the type of a variable where it is not explicitly typed.
let age = 18; // Number
age = 'string' //Error
Copy the code
Of course, if you declare a variable without specifying Any type, it defaults to Any, and Any subsequent assignments are accepted
let age // Any
age = 'string' //true
age = 18 //true
Copy the code
There is also a case where you use reference data types, such as multiple expression types inside an array. TypeScript deduces the most appropriate generic type based on the type of these expressions
let age=[18.'string'.null] // (string | number | null)[]
Copy the code
Types of assertions
One of the things that happens when we use TypeScript is that you know the type of the variable’s value better than the program does. Such as:
const tel = [110.120.119];
const emergency = tel.find((i) = > i ==110 || i==120); // number | undefined
Copy the code
Type assertions, however, tell the compiler that no special case has occurred in cases where TypeScript inferences assume undefined when we can be sure that it will not. There are two ways to define type assertions: first, by (XXX as type).
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Copy the code
XXX
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Copy the code
Note that in JSX files, there may be syntax conflicts in the way Angle brackets are written. Therefore, as inference is recommended
Part 06 – TypeScript类Classes
The classes class can be used to describe abstract characteristics of a specific class of things
The definition of a class
The use of classes here is no different from the use of methods in JS, containing the same members, namely properties, constructors, and methods. But it’s worth noting that in TS you have to set the initial values in properties or constructors at declaration time, not dynamically in constructors as in ES6
class student {
name: string;
age: num;
constructor(name: string, age: num) {
this.name = "Zhang";
this.age = 18;
}
study(course: string) :void {
console.log(`The ${this.name}This year,The ${this.age}Years old. He's going to work today${course}Class `); }}Copy the code
Class inheritance
Classes in TypeScript can also inherit instances of their parent classes and have properties and methods in the parent class. Also use super to call instances of the parent class and get this of the parent class, etc. And inheritance can still be implemented through the extends keyword. This reusability of enhanced code is preserved in TypeScript.
class student {
public name: string;
public age: num;
constructor(name: string, age: num) {
this.name = "Zhang";
this.age = 18;
}
study(course: string) :void {
console.log(`The ${this.name}This year,The ${this.age}Years old. He's going to work today${course}Class `); }}class four extends student {
constructor(name: string, age: num) {
super(name, age);
this.name=name
this.age=age
}
study(grade: string) :void {
console.log(`The ${this.name}This year,${grade}Grade `);
super.study("Chinese"); }}const Li = new four("Bill".22);
Li.study("Three");
// Li Si is in grade three
// Li Si is 22 years old. He is going to have Chinese class today
Copy the code
Class modifier
Private Private attributes can only be accessed inside the current class
class student {
private goodStudent: string = "Merit Student";
}
class four extends student {
constructor() {
super(a);this.goodStudent // The Error attribute "goodStudent" is private and can only be accessed in class "student".}}const Li = new four("Bill".22);
Li.study("Three");
Li.goodStudent // The Error attribute "goodStudent" is private and can only be accessed in class "student".
Copy the code
However, when we hand private modifiers to constructor, they can neither be inherited nor instantiated externally, and can only be implemented through static methods inside the class.
class student {
private constructor(name: string, age: num){}static go() {
return newstudent(); }}class four extends student { // Cannot extend class "student". Class constructors are marked private.
}
const Li = new student(); // Cannot extend class "student". Class constructors are marked private.
const create = Li.go() //Success
Copy the code
Protected # Properties can only be accessed from inside the class (they can be used in inherited subclasses)
class student {
protected goodStudent: string = "Merit Student";
}
class four extends student {
constructor() {
super(a);this.goodStudent // Success}}const Li = new four("Bill".22);
Li.study("Three");
Li.goodStudent // The Error attribute "goodStudent" is private and can only be accessed in class "student".
Copy the code
Protected is used in constructors like private, but can be inherited
Readonly Read-only properties Read-only properties must be initialized at declaration time or in a constructor
class Student {
readonly name: string;
readonly age: number = 18;
constructor(studentName: string) {
this.name = studentName; }}class Four extends Student{
constructor(name:string){
super(name)
console.log(this.name); }}let three = new Student("Zhang");
let four = new Four("Bill");
three.name = "Fifty"; / / error! "Name" cannot be assigned because it is a read-only property.
four.name = "Daisy"; / / error! "Name" cannot be assigned because it is a read-only property.
Copy the code
Class accessor
TypeScript supports intercepting access to object members through getters and setters. It helps you control access to object members. For example, in the following method, we use the set method to determine whether the password is correct or not before changing the permission. If the permission cannot be controlled, the fullname can still get the old name through get.
let passcode = "Password";
class Employee {
private _fullName: string = "Old name";
get fullName() :string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "Password") {
this._fullName = newName;
} else {
console.log("Permission update failed"); }}}let employee = new Employee();
employee.fullName = "New name";
if (employee.fullName) {
console.log(employee.fullName);
}
Copy the code
An abstract class
Similar to how interfaces are used, they are also abstractions of members, but unlike interfaces, abstract classes can contain implementation details of members. The abstract keyword is used to declare and define abstract classes and to define abstract methods within an abstract class. However, a dummy class cannot be created as an instance. It can only be inherited by a derived subclass, and super methods cannot access abstract methods in their parent class.
abstract class Family {
people(name: string.relation: string) :void {
console.log(I `${relation}call${name}`);
}
abstract eat(food: string) :void;
}
class Father extends Family {
eat(food: string) :void {
console.log(food); }}const father = new Father();
const family = new Family(); / / the Error! Unable to create an instance of an abstract class.
father.eat(The word "apple");
Copy the code
Part 07 – TypeScript Interfaces
You can think of an interface as a specification that can be used to regulate the structure and type of objects. In TypeScript, interfaces are conventions about which members an object contains and how their types are specified.
Interface Interface
We use the interface keyword to specify the structure of the object’s members, which means that you must have all the members bound by the interface, and the members must conform to the specified type.
interface rsvrConfig {
resName: string;
resCode: number;
resType: Array<string>;
}
function createRsvr(rsvrData: rsvrConfig) {
console.log(rsvrData.resName);
console.log(rsvrData.resCode);
console.log(rsvrData.resType);
}
const rsvrData = {
resName: "Huairou Reservoir".resCode: 2002011.resType: ["PP"."ZZ"."ZQ"]}; createRsvr(rsvrData);Copy the code
Optional attribute
Optional attributes are just like when you define an interface, there are some attributes that are optional that don’t affect the use, so we’re going to add one to the definition, right? To represent.
interfacersvrConfig { resName? :string;
resCode: number;
}
function createRsvr(rsvrData: rsvrConfig) {
console.log(rsvrData.resCode);
}
const rsvrData = {
resCode: 2002011}; createRsvr(rsvrData);Copy the code
One of the benefits of optional attributes is that you can pre-define possible attributes, and another is that you can catch errors when references to non-existent attributes. For example: prompt when the property name is misspelled
Read-only property
Some object properties can only change their value when the object is created. You can specify read-only properties with readonly before the property name
interface rsvrConfig {
readonly resName: string;
}
function createRsvr(rsvrData: rsvrConfig) {
rsvrData.resName = 'Miyun Reservoir' / /!!!!!! Error Read-only attribute
console.log(rsvrData.resName);
}
const rsvrData = {
resName: 'Huairou Reservoir'}; createRsvr(rsvrData);Copy the code
TypeScript also has the ReadonlyArray
type, which is similar to Array
except that all mutable methods are removed, thus ensuring that arrays can never be modified after they are created:
interface rsvrConfig {
resType: ReadonlyArray<string>;
}
function createRsvr(rsvrData: rsvrConfig) {
rsvrData.resType[0] = "Miyun Reservoir"; / /!!!!!! Error Read-only attribute
console.log(rsvrData.resType);
}
const rsvrData = {
resType: ["Huairou Reservoir"]}; createRsvr(rsvrData);Copy the code
Function types
In addition to describing ordinary objects with attributes, interfaces can also describe function types. It is equivalent to defining the types of arguments to a function. The arguments to the function are checked one by one to ensure that the argument types in the corresponding positions are compatible.
interface SearchFunc {
(source: string.subString: string) :boolean;
}
let mySearch: SearchFunc;
mySearch = function (source: string, subString: string) :boolean {
let result = source.search(subString);
return result > -1;
};
Copy the code
Dynamic type
When you do not know whether your interface needs to add other unknown fields, you can use the form [auto:type]:type to define dynamic typing.
interface StringArray {
[index: number] :string;
}
let myArray: StringArray;
myArray = ["Bob"."Fred"];
let myStr: string = myArray[0];
Copy the code
interface StringName {
[name: string] :string;
}
letnameDate: StringName; NameDate = {Huairou Reservoir:"1", Miyun Reservoir:"1", Black Mountain Reservoir:"1"};Copy the code
TypeScript supports two index signatures: strings and numbers. You can use both types of indexes.
nameDate[0] = "A cloud";
nameDate["1"] = "Softer";
// nameDate={ '0': '密云', '1': '怀柔' }
myArray[0] = "A cloud";
myArray["1"] = "Softer";
// myArray=[' miyun ', 'huailu']
Copy the code
Finally, you can set the index signature to read-only, thus preventing index assignment.
interface ReadonlyStringArray {
readonly [index: number] :string;
}
let myArray: ReadonlyStringArray = ["Alice"."Bob"];
myArray[2] = "Mallory"; // error!
Copy the code
Class types
TypeScript uses interfaces to explicitly force a class to conform to a definition. Here we use implements to define a member type that the class must implement. Of course, you can also make only one rule for each interface, through interface concatenation, to make the definition of the interface more detailed.
interface FamilyRespons {
cook(doing: string) :void;
clean(doing: string) :void;
}
interface Teach {
teach(type: string) :void;
}
interface Study {
study(time: num): void;
}
class Father implements FamilyRespons.Teach {
cook(doing: string) :void {}
clean(doing: string) :void {}
teach(type: string) :void{}}class Children implements FamilyRespons.Study {
cook(doing: string) :void {}
clean(doing: string) :void {}
study(time: num): void{}}Copy the code
Interface inheritance
Like classes, interfaces can inherit from each other, giving them more flexibility to split them into reusable modules using the extends keyword, and an interface can inherit multiple interfaces to create composite interfaces.
interface Background {
color: string;
}
interface Content {
width: number;
}
interface BoxStyle extends Background, Content {
borderWidth: number;
}
let boxCss: BoxStyle = {
color: "red".width: 100.borderWidth: 1};Copy the code
Part 08 – TypeScript generics
The definition of generics
Generics are when we define functions, interfaces, etc., instead of specifying their types, we specify their characteristics when we use them. For example, when we declare a function we do not declare the type of the argument, and when we use a call we define the type passed in by the need to pass the argument.
function identity<T> (arg: T) :T {
return arg;
}
let output = identity<string> ("myString"); // function identity<string>(arg: string): string
Copy the code
Typically we represent type variables by
. T helps us modify the type that is passed in for the user. Once we define a generic function, we can use it by passing in the desired type in <>. For example,
Generic variables
When creating a generic function, you must use it as a generic type within the function body. For example, the following situation is wrong
function loggingIdentity<T> (arg: T) :T {
console.log(arg.length); // Error: attribute "length" does not exist on type "T"
return arg;
}
Copy the code
When you’re an arbitrary type you can pass in number so there’s no length property, so we can define this generic by creating an array.
function loggingIdentity<T> (arg: T[]) :T[] {
console.log(arg.length); // Success
return arg;
}
Copy the code
When you define an array and the values inside the array are generic, the length method makes sense.
A generic interface
First, the types of generic functions are no different from those of non-generic functions, and interfaces can also be defined through generics, enclosing generic types by <>.
interface TestInterface<T> {
<T>(arg: T): T;
}
function FunctionInterface<T> (arg: T) :T {
return arg;
}
let myIdentity: TestInterface<number> = FunctionInterface;
Copy the code
A generic class
Generic classes look much like generic interfaces. Generic classes also use <> to enclose generic types after the class name.
class TestClasses<T> { value? : T; add? :(x: T, y: T) = > T;
}
let doSomeThing = new TestClasses<string> (); doSomeThing.value ='creatString';
doSomeThing.add = (x, y) = > x + y;
Copy the code
Generic constraint
Taking a generic variable as an example, we want to access the length attribute of the arG inside the function body, but because the type of the ARG is uncertain, we need to constrain the type of the ARG to include at least that attribute.
interface Length {
length: number;
}
function loggingIdentity<T extends Length> (arg: T) :T {
console.log(arg.length); // Success
return arg;
}
loggingIdentity(10); // Error has no length attribute
loggingIdentity({ length: 10 });
Copy the code
When T inherits the generic Length, the argument must contain the necessary attributes, so the use of Length becomes reasonable.
Part 09 – TypeScript declaration merge
Combined interface
When two interfaces with the same name are merged, the members of both interfaces are put into one interface with the same name.
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
let box: Box = {height: 5.width: 6.scale: 10};
Copy the code
Note that when interface A is merged with subsequent interface A, the subsequent interface has higher priority. This means that later interfaces will be overloaded at the front.
interface Box {
scale: number;
height: number;
width: number;
}
Copy the code
At the end
Because at present, I only study according to part of the 3.1 version of the Chinese official website. Therefore, the new features after 3.1 have not been studied and exported in detail. I’ll follow up on the typeScript official release with a closer look and continue to output what I’ve learned. As a new blogger, I hope you can provide me with more advice to help me improve. If feel write bad hope everybody big guy light spray! Thank you so much!