Some time ago, a friend of mine recommended TypeScript to me. He said it was so cool to write that he asked me to give it a try while I was still working on it. Just at that time busy, have no time to see. I’ve been busy lately, so take the time to check out TypeScript. To put it simply, TS mainly provides dynamic type check, and the interface interface function will be very helpful in the development of projects. TypeScript is a superset of JavaScript. It has a lot to do with JavaScript.
Typescript-related commands
Tsc-init //ts file is compiled into JS file tsc-w // monitor file compilation in real time, i.e. write ts code once and save js code can be seenCopy the code
After running Tsc-init, a tsconfig.json configuration file is generated
Reverence every line of code, every commitment
function
JavaScript
TypeScript
ts
You need to validate function argument types, including string and number, string[],number[], and tuples (=> learning to enter tuples => learning to primitive types). TypeScript functions can create named and anonymous functions
function add(x:number,y:number):number {
returnX + y} // named functionlet myAdd = function(x:number,y:number):number {
returnX + y} // anonymous functionCopy the code
We only type the anonymous function on the right side of the code, while myAdd on the left side of the equals sign is inferred by the assignment operation, writing the complete function type. (Type Inference: If no Type is explicitly specified, TypeScript inferences a Type according to the rules of Type Inference.)
let myAdd: (x:number,y:number) => number =
function(x: number,y:number):number { return x + y}
Copy the code
The function type has two parts: the parameter type and the return value type; In TypeScript type definitions, => is used to represent function definitions, with input types enclosed in parentheses on the left and output types on the right, unlike the arrow functions in ES6
Optional and default parameters
Every function argument in TypeScript is required. The number of arguments passed to the function must match the expected number of arguments, otherwise an error will be reported.
Required parameters
function buildName(firstName:string,lastName:string) {
return firstName + "" + lastName
}
letresult0 = buildName(12, 12); // Prompts that arguments of type 12 cannot be assigned to stringlet result1 = buildName('Bob') // The prompt should have two arguments, but only one is obtainedlet result2 = buildName('Bob'.'Adams'.'"sr') // The prompt should have two arguments, but only three were obtainedlet result3 = buildName("Bob"."Adams"); // Parameters are the same as those passed inCopy the code
Optional parameters
For optional parameters, we need to add? Next to the parameter name. , but optional arguments must be followed by arguments
functionselectParam(firstName:string,lastName? :string) {return firstName + "" + lastName
}
let selectParam1 = selectParam('bob')
let selectParam2 = selectParam('bob'.'Adam')
let selectParam2 = selectParam('bob'.'Adam') // Two variables cannot be redeclaredCopy the code
The default parameters
We can provide default values for arguments. If a parameter with a default value appears before a required parameter, the user must explicitly pass undefined to get the default value
function param(firstName:string,lastName = 'Smith') {
return firstName + ' ' + lastName
}
let param1 = param('bob')
let param2 = param('bob'.'Adam'.'kk') // The prompt parameter should be 1-2Copy the code
The remaining parameters
Mandatory parameters, default parameters and optional parameters are used to represent a certain parameter. Sometimes we do not know how many parameters to operate, we can use… To manipulate the remaining parameters
functionrestParam (firstName:string,... restOfName:string[]) {return firstName + "" + restOfName.join(' ')}let employName = restParam ('Joseph'."Samuel"."Bob") //restParam can be in a different formletrestParamFun:(fname:string,... rest:string[]) => string = restParamCopy the code
this
And arrow functions.
In JavaScript, the value of this is specified when the function is called. This is specified when TypeScript is created
interface Card { suit: string; card: number; } interface Deck { suits: string[]; cards: number[]; createCardPicker(this:Deck):()=>Card; //this points to Deck}let deck:Deck = {
suits:['hearts'.'spades'.'clubs'],
cards:Array(52),
createCardPicker:function(this:Deck) {
return() = > {let pickedCard = Math.floor(Math.random()*52)
let pickedSuit = Math.floor(pickedCard / 13);
return { suit: this.suits[pickedSuit],card:pickedCard % 13}
}
}
}
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
Copy the code
In JavaScript, this points to a window, but TypeScript doesn’t, because it specifies on which object this will be called
Basic types of
There are two types in JavaScript: primitive data types (Boolean, Number, String, NULL, undefined, Synmbol) and object types. In TypeScript, primitive data is also used. In order for a program to be valuable, we need to be able to handle the simplest units of data, numbers, strings
Numbers, strings, arrays
letDecLiteral :number = 6 // Number typelet name1:string = 'bob'// A string of characterslet sentence:string = `Hello, my name is ${name1}'// String templateletList0 :number[] = [1,2,3,4] //[] defines an arraylet list1:string[]=['12'.'12'.'90']
letList2 :Array<number> = [1,23,4]let list3:Array<string> = ['1'.'23'.'4'] //Array< element type >Copy the code
Array types have multiple ways of defining them in TypeScript, which is flexible
- Type + square bracket notation
letFibonacci :number[] = [1,2,3,4]// only the number type can be transmitted. Otherwise, an error message will be displayedCopy the code
- 2. Array generics (=> Skip to generics to learn)
letFibinacci: Array < number > = [1, 2, 3, 4]Copy the code
- 3. Use interfaces to represent arrays (=> skip to interfaces)
interface NumberArray {
[index:number]: number
}
letFibonacci: NumberArray = [1, 2, 3, 4]Copy the code
NumberArray is an array of numbers, index is the index type of the array, and: is an array of numbers.
tuplesTuple
Tuple types allow you to represent an array with a known number and type of elements. The elements need not be of the same type (arrays combine objects of the same type, whereas tuples combine objects of different types).
let x:[string,number];
x = ['Hello', 10]Copy the code
Enumeration: scenarios in which the value is limited
Let’s say there are only seven days in a week
enum Color { Red,Green,Blue}
let c:Color = Color.Green
Copy the code
any
A variable whose type is not known at the programming stage specifies a type. The value may be dynamically entered, but the value of a variable of type Object allows you to assign any value to it and cannot call a method on it. Using any causes the function to accept arguments of any type, which loses some information; If we pass in a number, we just know that any type of value can be returned
let list:any[] = ['Xcat Liu', 25, { website: 'http://xcatliu.com' }];
let notSure:any = 4
notSure = "maybe a string instead"
notSure = false
Copy the code
void
The type andany
Type the opposite
It means there is no type, when there is a function that does not return
function warnUser():void {
console.log("This is my waring message")}Copy the code
Undefined and null are not very useful in their own right: the Never type represents value types that Never exist
assertionsas
Trust me, I know what I’m doing, okay
let someValue:any = "this is a string"
letStrLength :number = (<string>someValue). Length // Angle bracket syntaxletstrLength1: number = (someValue as string).length; // One is the as syntaxCopy the code
Joint type: indicates that the value can be one of multiple types
letmyFavoriteNumber:string|number; / / connector | myFavoriteNumber ='seven'
myFavoriteNumber = 7
Copy the code
The generic
API
A special variable that represents a type, not a value
Generic function
function identity<T>(arg:T):T {
return arg;
}
let output = identity<string>("myString")
Copy the code
Difference: There is no difference between a generic function and a non-generic function, except that there is a type parameter first, like a function declaration
let myIdentity:<T>(arg:T) => T = identity
let myIdentity1:{ <T>(arg:T):T} = identity
Copy the code
We can define generic functions using object literals with call signatures. We can take the object literals as an interface, and a generic parameter as an argument to the entire interface, so that we know exactly which generic type to use
A generic interface
interface GenericIdentityFn {
<T>(arg:T):T
}
function identity<T>(arg:T):T {
return arg
}
let myIdentity:GenericIdentityFn = identity
Copy the code
Generic classes (=> Class learning)
Generic classes look much like generic interfaces, using (<>) to enclose generic types after the class name
class GenericNumber<T> {
zeroValue:T,
add:(x:T,y:T)=>T
}
let myGenericNumber = new GeneriNumber<number>()
Copy the code
Classes have two parts: a static part and an instance part. A generic class refers to an instance part, so static properties cannot use this generic type to define interfaces to describe constraints
Generic constraint
interface Lengthwise {
length:number
}
function loggingIdentity<T extends Lengthwise>(arg:T):T {
console.log(arg.length)
return arg
}
Copy the code
Extends extends extends an interface to restrict generic data structures
interface
TypeScript
inplements
Benefits of optional attributes: Possible attributes are defined and errors are caught when a non-existent attribute is referenced
Read-only properties (readonly)
Some object properties can only change the value of an object when it is just created
interface Point {
readonly x:number;
readonly y:number;
}
Copy the code
TypeScript has the ReadonlyArray
type, which is similar to Array
except that all mutable methods are removed to ensure that arrays can never be modified once created
readonly vs const
Const if we want to treat it as a variable, readonly if it is a property
Additional property checking
1. You can bypass these checks using type assertions (both forms of assertions)
letStrLength :number = (<string>someValue). Length // Angle bracket syntaxletStrLength1: number = (someValue as string). Length // a syntax for 'asCopy the code
2. Using index tabs, objects are assigned to another variable, and object literals are treated specially and subject to extra property checks when they are assigned to variables or passed as arguments
let squareOptions = { colour: "red", width: 100 }
let mySquare = createSquare(squareOptions)
Copy the code
3. Add a string index signature
interface SquareConfig { color? :string; width? :number; [propName:string]:any }Copy the code
Function types
Interfaces can describe the various shapes that objects have in JavaScript. Interfaces can also be described as function types in addition to ordinary objects. It has a call signature, a parameter list, and a function definition of the return value type. Each parameter in the parameter list needs a name and type. The parameter name of the function does not need to match the name defined in the interface
interface SearchFunc {
(source:string,subString:string):boolean;
}
let MySearch:SearchFunc;
MySearch = function(source:string,subString:string) {
let result = source.search(subString);
return result > -1
}
Copy the code
Indexable type
interface StringArray {
[index:number]:string
}
//let myArray:StringArray = ["Bob".'Fred']
let myArray:StringArray;
myArray = ["Bob".'Fred']
Copy the code
Class type implementation interface, using keywordsimplements
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime:Date;
constructor(h:number,m:number){}
}
Copy the code
Extends the interface keyword
interface Shape {
color:string;
}
interface PenStroke {
penWidth:number;
}
interface Square extends Shape,PenStroke {
sideLength:number
}
let square = <Square>{}
Copy the code
Extends extends extends from a class. You can then use or override the methods of the parent class.
Implements multiple interfaces, whose methods are generally empty and must be overridden to use them
class
this
Class: Defines the abstract characteristics of a thing, including its properties and methods
Object: An instance of a class, generated by new
Three main features of OOP: encapsulation, inheritance and polymorphism
Encapsulation: Hides data operation details and exposes only external interfaces. In this way, the external end can access the object through external interfaces without requiring (or impossible) to know the details. In addition, external devices cannot arbitrarily change the internal data of the object
Inheritance: A subclass inherits its parent class. A subclass has all the characteristics of its parent class and some more specific characteristics
Polymorphism: the generation by inheritance of related species that respond differently to the same approach. For example, Cat and Dog both inherit from Animal, but each implements its own eat method. At this point, for an instance, we can call the eat method without knowing whether it is Cat or Dog, and the program will automatically determine how to execute eat
Accessors (getters & setters) : Used to change the read and assignment behavior of properties
Modifiers: Modifiers are keywords that qualify the properties of members or types
Abstract Class: An Abstract Class is a base Class that provides inheritance from other classes. Abstract classes are not allowed to be instantiated. Abstract methods of an Abstract Class must be implemented in subclasses
Interface: Properties and methods that are common among different classes. An Interface can be abstracted as an Interface, which can be implemented by a class. A class can only inherit from another class, but implements multiple interfaces
class Greeter {
greeting:string;
constructor(message:string) {
this.greeting = message
}
greet() {
return "Hello" + this.greeting
}
}
let greeter = new Greeter("World")
Copy the code
New constructs an instance of the Greeter class, calls the previously defined constructor, creates a new object of type Greeter, and executes the constructor to initialize it
inheritance
Extending an existing class by inheritance, the base class is usually called Animal, and the derived class is often called Dog.
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters:number = 0) {
console.log(`Animal moved ${distanceInMeters}`)
}
}
class Dog extends Animal {
constructor(name: string) { super(name); }
bark() {
console.log("woof woof")
}
move(distanceInMeters = 5) {
super.move(distanceInMeters)
}
}
const dog = new Dog()
dog.bark()
dog.move(10)
Copy the code
The derived class contains a constructor that must call super(), which executes the base class function. Super () must be called before the constructor can access the this property. This is an important rule that TypeScript enforces
There are both private and protected modifiers
In all TypeScript, members default to public
When a member is marked private, he cannot declare his external access
Protected and private modifiers behave similarly, with one difference: protected members are still accessible in derived classes.
The readonly keyword sets the property to read-only, which must be initialized in a declaration or constructor
TypeScript uses the structural type system. When we compare two different types, we consider the members of the type to be type compatible if they are compatible
accessor
TypeScript supports intercepting access to object members via getters/setters
let passcode = 'secret passcode'
class Employee {
private _fullName:string;
get fullName():string {
return this._fullName
}
set fullName(newName:string){
if (passcode && passcode == "secret passcode") {
this._fullName = newName
} else {
console.log("Error: Unauthorized update of employee!"); }}}let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
Copy the code
Static attributes
When an attribute exists only on the class itself and not on the class instance, it is called a static member identifier
An abstract class
Used as base classes for other derived classes, they are generally not instantiated directly. Abstract methods in abstract classes do not contain concrete implementations and must be implemented in derived classes. The syntax of an abstract method is similar to that of an interface method in that it defines only the method signature, but not the method body. Abstract classes can contain implementation details for members and must contain an Abstract keyword identifier and access modifiers
abstract class Animal {
abstract makeSound():void
move():void {
console.log('roaming the earch... ')}}Copy the code
Use classes as interfaces
A class definition creates two things: an instance of the class and a constructor. Classes can create types, so you can use classes where interfaces are allowed
class Point {
x:number;
y:number;
}
interface Point3d extends Point {
z:number
}
let point3d:Point3d = {x:1,y:2,z:3}
Copy the code
Built-in objects
There are many built-in objects in JavaScript that can be treated directly as defined types in TypeScript
let b:Boolean = new Boolean(1)
let c:Error = new Error('Error occurred')
let d:Date = new Date()
let r:RegExp = /[a-z]/
Copy the code
DOM and BOM provide built-in objects that are often used in TypeScript
Temporarily write here first, next time continue, beginners do not know a lot of places, welcome correction, learning exchange
I seem to work overtime every day and always come home late. One of the main reasons I learned TypeScript was because of the strict code requirements that prevent future bugs. In the process of project development, I wrote a common method to parse the data format sent to me by the back end. Suddenly one day, the data structure sent to me by the back end changed from a string to an array, and the data structure of one or two interfaces changed, but most of the data structure remained unchanged. It took me quite a while to get page errors, line by line of code, and finally to find the public method. At that point I was thinking how nice Java would be to define data types directly. Saved me from the same situation. Then I learned that TypeScript also works. Grow to like him. The code has strict requirements, debug in advance, recently ready to learn, in the busy to learn, can be convenient.
When studying TypeScript official documentation, I use Java syntax analogies, and I feel the syntax is similar. I also keep asking my colleagues if you have the implements and extends syntax in Java and the difference between them in Java. My colleagues thought I was learning Java. I told them I was learning the front end by analogy
I have TypeScript materials for recommendation and resource sharing. I have read the official documents twice, and I am ready to practice with the project in the future. If you have relevant development experience, imagine you learn, communicate haha, need an old driver to take me haha