preface
Why learn TypeScript?
- From a development perspective,
TypeScript
As a strongly typed language, attributes have type constraints. Reduced unnecessary parameter types in daily developmentBUG
When you are using a function wrapped by a colleague, the type does not know how to pass, in developmentTS
“, it will give you a very type-friendly prompt, so you know what parameters the function needs to pass and what type the parameters are. - In terms of project structure, use
TypeScript
The project can be well controlled by establishing the type management of each module throughinterface
orTypes of assertions
To manage the types in the project and use the types in the corresponding modules. When the project needs to be updated iteratively, only the corresponding module types need to be changed. - Tell from front end overall view, community 3 big frames already union
TypeScript
Yes, the community is perfect. It’s overIs it time to learn the TypeScript phase
.
Last year, there were a lot of people who were hesitant to learn TypeScript. Many of them were misled by community posts about TypeScript being AnyScript.
TypeScript is a bit of a learning cost for those of you who are not familiar with strongly typed languages, and the early stages of development in TypeScript can be bloated and seem like a lot of useless code, but you can have fun with TypeScript later on.
Learning TypeScript also gives you a competitive edge in the workplace. If you’ve already worked on some projects with TypeScript, you’ll be more likely to be considered and your salary will rise. There is a long way to go on the front end, new technologies/frameworks are updated very quickly, and ultimately JavaScript is essential.
Let’s take a look at TypeScript. This article takes a look at standard TypeScript documents and shows you how to use TypeScript in more general terms.
This mapping
TypeScript
First, installation environment
#npm install -g typescript
Copy the code
1.1 VSCode Configures automatic file compilation
#1.TSC --init automatically generates tsconfig.json in tsconfig.json2.Task - Run task monitor tsconfig.jsonCopy the code
Second, basic grammar
2.1 an array
Define the use
Let array name: type [] = []
var arr:number[] = [1.2.3];
console.log(arr);
Let Array name: Array[type] = []
var newArr:Array<number> = [1.2.3];
console.log(newArr)
Copy the code
2.2 yuan group
It represents the number of existing elements and an array of element types, which can be different.
Access the meta length and elements
var strArr:[number,string,boolean] = [22.'test'.false]
console.log(strArr.length)
console.log(strArr[0] # it can only enter the content in the first order of type, otherwise an error is reportedCopy the code
2.3 the enumeration enum
Enum types complement the JavaScript standard data types.
- If no index is specified for the enumeration, the default is 0 and passes
Enumeration object [index]
You can get the value- Passes if the enumeration index is specified as a string
Enumeration. property
Gets its value
enum Sex {Man,Woman}
let m:Sex = Sex.Man;
console.log(m) / / 0
let w: string = Sex[1]
console.log(w) //Woman
enum Animal {Dog = 3, Cat, Tiger};
console.log(Animal[5]) //Tiger
enum info {student = 'students', teacher = 'teachers', parent = 'parents' };
console.log(info.teacher) / / the teacher
Copy the code
2.4 Any type
Any is of any type and is usually used when retrieving the DOM
// Any type
const newArrs:any = ['Test different data'.222.false]
console.log(newArrs) #'Test different data'.222.false[/ en] [/ en] [/ en] [/ en] [/ en] [/ en] [/ en] [/ en] [/ enany
Copy the code
2.5 undefined type
let num:number | undefined ;
console.log(num) // output undefined, but no error
let newNum:number | undefined = 33;
console.log(newNum) / / output 33
Copy the code
2.6 never type
Never represents a nonexistent value type and is often used as the return type of a function that throws an exception or loops indefinitely
Application scenarios1.Throwing errorconst errDate = (message:string): never= > {
throw new Error(message)
}
#2.Infinite loopconst date_for = (): never= > {
while(true{}} # The never type is a subtype of any type. No subtype of never can be assigned to a type of never, and the never type can be assigned to any typeCopy the code
2.7 void type
Void is a function that has no type and is usually used when a function has no return value
If the method type isnumber, the content must be returned, and the content must be a numberfunction add() :number{
return 2323; } # if the method type isvoidThere is no need to return the contentfunction getAdd() :void{
console.log('test'} # if the method type isany, can return any typefunction getAny() :any{
return 999 + 'Hello TypeScript'
}
console.log(getAny())//999 'Hello TypeScript'
Copy the code
Third, type assertion
What is a type assertion?
- Type assertions are used when you define a variable without knowing what type it is at first, but when you use it you know what type it is.
3.1 The first writing method is Angle brackets
const str = 'test'
const resLength : number = (<string>str).length
Copy the code
3.2 The second way is as
const str = 'test'
const resLength : number = (str as string).length
Copy the code
Four, interface
One of TypeScript’s core tenets is type-checking of the structure a value has.
When validating a type, the order does not affect validation.
In simple terms, it is the definition of a type constraint, and when you use this definition interface, it will follow the type defined in the docking port.
As long as it does not satisfy any of the attributes in the interface, it will not pass.
4.1 Optional Attributes of the Interface
Optional attributes can be used when interface attributes are not required in all cases, but only when certain conditions are met
Format: Attributes? Type:
interface Login{
userName: string,
password: string, auth ? : string }function getLogin(obj: Login) {
if(obj.auth == 'Administrator') {
console.log('You can view all menus')}else {
console.log('You have low permissions and cannot view it at present')
}
}
getLogin({
userName:'zhangsanfeng'.password: '12121121sd'.auth: 'Administrator'
}) // You can view all menus
getLogin({
userName:'zhangsanfeng'.password: '12121121sd'
}) // Your permission is too low to view
Copy the code
4.2 Interface read-only Properties
Read-only property: this means that once a property is assigned a value, it cannot be changed.
Format: readonly Property: type
interface Menus { readonly title? :string, icon? :string, readonly path? :string, readonly Layout? :string }function getMenuInfo(data:Menus){
console.log(data)
data.icon = 'Modify icon' // It can be modified
// data.path = '/home' error, cannot be modified, the interface attribute is read-only
console.log(data)
}
getMenuInfo({
title: 'home'.icon:'homes'.path:'/home'.Layout: 'Layput'
})
Copy the code
4.3 Types of interface functions
Used to constrain function passing parameter types
- For type checking of function types, function parameter names need not match the names defined in the interface.
- Format:
(Parameter 1: type, parameter 2: type) : return value type
// Get user information
interface UserInfo {
(name: string,adress: string,phone: number) : string
}
let getUsefInfo:UserInfo = function(name,adress,phone){
return `${name}To live in${adress}, the mobile phone number is${phone}`
}
console.log(getUsefInfo('Zhang Feng'.Tianjin Nankai District XX Community.188888888))
Copy the code
4.4 Interface indexable type
When defining an array, you can define an index type interface that restricts what types of values it must pass.
Access: by variable [index]
interface Code{
[index : number] : string
}
let errCode : Code = ['200 success'.'301 Redirect '.'400 Client error '.'500 Server error ']
console.log(errCode[3]) //500 server error
Copy the code
4.5 Type Interface Implementation
Interfaces describe the public parts of a class, not the public and private parts. It doesn’t help you check if the class has some private members.
interface Animals {
eye: number,
leg: number,
}
class Dog implements Animals {
eye: number;
leg: number;
kind: string
constructor(eye: number, leg: number, kind: string) {
this.eye = eye
this.leg = leg
this.kind = kind
}
getDogInfo(){
console.log(` varieties forThe ${this.kind}, there areThe ${this.eye}Eye,The ${this.leg}Leg `)}}let hashiqi = new Dog(2.4.'Husky');
hashiqi.getDogInfo() // The breed is husky, with 2 eyes and 4 legs
Copy the code
4.6 Interface Inheritance (All in One)
Interfaces can be inherited from each other, which allows for more flexibility in splitting interfaces into reusable modules.
interface Shape1 {
data: string
}
interface Shape2 extends Shape1{
code: number
Shape2 has the characteristics of Shape1
}
class Message implements Shape2 {
code: number;
data: string;
constructor(code : number,data: string) {
this.code = code;
this.data = data
}
getCodeInfo(){
console.log('Status code isThe ${this.code}, the return message isThe ${this.data}`)}}let err = new Message(500.'Server error')
err.getCodeInfo() // The status code is 500, and the return message is server error
Copy the code
4.7 Interface Inheritance Classes
When an interface inherits from a class, the interface also owns the attributes and methods of that class.
When another class implements this interface, it implements both the properties and methods of the interface and inherits the properties and methods of the class
class Log {
time: string = '2020-11-2';
getLog(){
console.log('test')
}
}
interface Shape3 extends Log{
message : string
}
class ErrLog implements Shape3 {
message: string ;
time: string;
constructor(message: string, time: string) {
this.message = message;
this.time = time
}
getLog(): void {
console.log("Method not implemented."); }}let errs = new ErrLog('test'.'2020-11-2')
errs.getLog() //Method not implemented.
Copy the code
Five, generics
Those of you who have been exposed to JAVA should be familiar with this.
We, on the front end, are probably hearing this concept for the first time. As you can see from the literal meaning, it refers to a wide range of types.
- Purpose: : Avoid duplicate code, code redundancy
But it’s different from any.
Any type: If a function is of type any, its arguments can be of any type. Generally, the type passed in should be the same as the type returned. If a string is passed in, we don’t know what type it returns.
Generics: This allows the return type to be the same as the incoming type, so that we know exactly what type the function returns.
5.1 Generic Interfaces
Generic interfaces can be understood as follows:
You can use a generic interface when you need to type an interface, but you don’t know what the property type is, right
You can specify multiple generic types for the interface, or you can specify a single parameter. When used, specify the parameter type.
interface User <T,S,Y> {
name: T;
hobby: S;
age: Y;
}
class People implements User<String.String.Number> {
name: String;
hobby: String;
age: Number;
constructor(name:string,hobby:string,age:number){
this.name = name;
this.hobby = hobby;
this.age = age;
}
getInfo(){
console.log(this.name+"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"+this.hobby)
console.log(`The ${this.name}The age ofThe ${this.age}`)}}let xiaoZhou = new People('little weeks'.'Knock code'.22)
xiaoZhou.getInfo()
// Xiao Zhou ------------------
// Xiao Zhou's age is 22
Copy the code
5.2 Generic functions
Define a generic function that makes the input parameter type and return value type the same.
The generic flag is usually capitalized, and the T can be changed at will
Format: function name <T> (parameter 1: T) : return value type TCopy the code
function genericity<T> (data: T) : T {
console.log(data)
return data
}
genericity("Test")
genericity(Awesome!)
genericity(['front end'.'back-end'.'the cloud'])
Copy the code
5.3 a generic class
- What are generic classes
It specifies the types of attributes and methods in a class and must be consistent with the types defined by the type.
- The role of generic classes
This helps us ensure that all attributes of a class are using the same type
- Use the format
classThe name of the class"T> { name! : T; hobby! : T; } # all types of this class are numberletInstance =newThe name of the class < number > ();Copy the code
class GenericityA<X>{ sex! : X; age! : X; }let gen = new GenericityA<number> ();// gen.sex = 'test' error
gen.age = 3
console.log(gen.age)
Copy the code
5.4 Generic constraints
- Interface constraint
- By defining the interface, the generic function inherits the interface, and the parameters must implement the attributes in the interface, thus fulfilling the constraint of the generic function
- To restrain
- By assigning the generics of a class to another class, you specify that the types of class generics are all of another class
# the first// Define the interface
interface DataInfo{
title: string,
price: number
}
// The generic function inherits the interface to constrain the parameter type. If the parameter passed does not contain the interface attribute, the compilation fails
function getDataInfos< T extends DataInfo> (obj: T) : T {
return obj
}
let book = {
title: 'Front end advance'.price: 50.author: 'new'
}
console.log(getDataInfos(book)) //{ title: '前端进阶', price: 50, author: '小新' }
Copy the code
# the second// Constrain by class
class Login{
username: string;
password: string;
constructor(username: string,password:string){
this.username = username
this.password = password
}
}
class Mysql<T>{
login<T>(info:T):T{
return info
}
}
let x = new Login('admin'.'12345');
let mysql = new Mysql<Login>();
console.log(mysql.login(x)) //Login { username: 'admin', password: '12345' }
Copy the code
Six, Class
Speaking of classes, do back-end friends should all know that the front end in ES6, the emergence of the Class Class keyword.
What are the characteristics of Class
- attribute
- The constructor
- methods
- inheritance
extends
- Property/method modifiers
- Static attributes
- An abstract class
- accessor
getters/setters
6.1 modifier
public
A total of the
When the property/method modifier is public, it is added by default if it does not precede it, and we can freely access the members defined in the program.
class Fruit {
public name: string;
price: number;
// The above is equivalent
constructor(name: string, price: number) {
this.name = name;
this.price = price
}
getFruitInfo(){
console.log('The fruit you want to buy is${name}, the price forThe ${this.price}`)}}Copy the code
private
private
When a member is marked private, it cannot be accessed outside the class in which it is declared.
class Fruit {
public name: string;
private price: number;
// The above is equivalent
constructor(name: string, price: number) {
this.name = name;
this.price = price
}
getFruitInfo(){
console.log('The fruit you want to buy is${name}, the price forThe ${this.price}`)}}const apple = new Fruit('apple'.22)
// console.log(apple.price) reported an error. Instances cannot access private properties
Copy the code
protected
The protected
Protected modifiers behave much like private modifiers, except that protected members are still accessible in derived classes. Protected properties cannot be accessed through instances.
class A {
protected name : string;
protected age : number;
constructor(name: string , age: number) {
this.name = name;
this.age = age
}
getA(){
console.log('A')}}class B extends A {
protected job : string;
constructor(name: string, job: string,age: number) {
super(name,age)
this.job = job
}
getB(){
console.log(` name for BThe ${this.name}&& age wasThe ${this.age}For && professionThe ${this.job}, `)}}let b = new B('a little'.'Front End Engineer'.22)
b.getA() //A
b.getB() //B's name is Xiao Fei, age is 22, and career is front-end engineer.
// console.log(b.name) failed to be accessed. Protected members can only be accessed from derived classes, not from instances.
Copy the code
6.2 Static Attributes
The static members (properties and methods) of a class are only accessible through the class.
Definition: static properties/static methods
class Food {
public name: string;
private price: number;
static adress: string = 'sichuan';
// The above is equivalent
constructor(name: string, price: number) {
this.name = name;
this.price = price
}
getFruitInfo(){
console.log('The items you want to purchase are${name}, the price forThe ${this.price}`)}}const spicy = new Food('spicy dry tofu'.3)
console.log(Food.adress) / / in sichuan
Console. log(spicy. Adress) reported an error that instances of a class cannot access static properties of the class. It can only be accessed through class.properties
Copy the code
6.3 inheritanceextend
The idea of inheritance is easy to understand. When a subclass inherits from a parent class, the subclass has the characteristics (properties) and behaviors (methods) of the parent class,
class T {
name:string;
constructor(name:string){
this.name = name
}
getNames(){
console.log('Inherited class T')}}class S extends T {
constructor(name:string){
// Derived classes have T attributes and methods
super(name)
}
getName(){
console.log(this.name)
}
}
let ss = new S('Test inheritance')
ss.getName()
ss.getNames()
// Test inheritance
// Inherit class T
Copy the code
6.4 the abstract class
- Abstract classes can contain implementation details of members.
abstract
Keywords are used to define abstract classes and abstract methods within abstract classes.- Abstract methods in abstract classes contain no concrete implementation and must be implemented in derived classes.
abstract class E{
abstract name: string;
abstract speak():void;
abstract play():void;
}
class F implements E {
name: string;
constructor(name:string){
this.name = name
}
// Derived class F must implement the methods and attributes of abstract class E
speak(): void {
console.log('Chat enabled')
}
play(): void {
console.log('Entertaining')}get(){
console.log(this.name)
}
}
let f = new F('test');
f.play() // It can be used for entertainment
f.get() / / test
f.speak() // Have chat function
Copy the code
Seven, the function in TS
Function types include parameter types and return value types
7.1 Function Adds a return value type
After each parameter is typed, the return value type is added to the function itself.
TypeScript can automatically infer the return value type from the return statement, so we typically omit it.
Here are two ways to write functions in TS
// The first way
let getInterFaceInfo : (obj:object) = > void = function(obj){
console.log(obj)
}
let infos: object = {
code: 200.message: 'Sent successfully'
}
getInterFaceInfo(infos)
// The second way
function getCode(code: number, message:string) : void {
console.log(` code for${code}The message to${message}`)
}
getCode(200.'Accept success')
Copy the code
7.2 This parameter is optional/default
In JavaScript, each parameter is optional and can be passed or not. When no parameter is passed, its value is undefined.
In TypeScript we can use it next to parameter names, right? Realize the function of optional parameters.
- Optional parameters must be placed after required parameters.
Format: function name (variable name? : type: type {}Copy the code
- Default parameter, which specifies a default value when passing the parameter
Format: function name (variable name: type = "xx") : type {}Copy the code
// This parameter is optional
function getNetWork(ip:string,domain:string,agreement? :string){
console.log('IP address is:${ip}, the domain name for${domain}, the agreement for${agreement}`)
}
getNetWork('127.0.0.1'.'www.xiaomi.com') // The IP address is 127.0.0.1. The domain name is www.xiaomi.com. The protocol is undefined
// Default parameters
function getNetWorks(ip:string,domain:string,agreement:string = 'http'){
console.log('IP address is:${ip}, the domain name for${domain}, the agreement for${agreement}`)
}
getNetWorks('127.0.0.1'.'www.xiaomi.com') // The IP address is 127.0.0.1, domain name is www.xiaomi.com, and protocol is HTTP
Copy the code
7.3 Remaining Parameters of the Function
Sometimes, you want to manipulate multiple arguments at once, or you don’t know how many arguments will be passed in.
In JavaScript, you can use arguments to access all incoming arguments.
In TypeScript, you can put all arguments in a single variable, preceded by… Represents remaining parameters.
Pay attention to
Access directly through variables
It can also be accessed by index
Only one remaining parameter can be defined, after the default parameter and optional parameter
function getNumberInfo(num:number,... peopleArray: string []) {
console.log(The number of personnel is${num}And members of${peopleArray}`) // You can also get elements by index
console.log(The number of personnel is${num}And members of${peopleArray[1]}`)
}
getNumberInfo(4.'Ming'.'xiao li'.'little red'.'zhang')
// The number of staff is 4, members are Xiao Ming, Xiao Li, Xiao Hong, Xiao Zhang
// The number of staff is 4, and the members are Xiao Li
Copy the code
Eight, the enumeration
Enumerations clearly express a set of correspondences.
TypeScript supports numeric and string-based enumerations.
8.1 Enumeration
The default enumeration order starts with 0 and then increases automatically.
The enumeration order can also specify a value that continues to be preceded by 0
access
- through
Enumeration. property
Access toThe serial number
- through
Enumeration name [ordinal number]
Access toThe property name
enum Sex {
x,
man = 4,
woman
}
console.log(Sex.x) / / 0
console.log('Xiao Hong's gender is${Sex[5]}`) // Xiao Hong's gender is Woman
console.log('Back end accepts little Red's gender ID${Sex.woman}`) // The backend accepts red's gender ID 5
Copy the code
8.2 Enumeration of Strings
enum Job {
frontEnd = 'front end',
backEnd = 'back-end'
}
console.log(Job) //{frontEnd: 'front ', backEnd:' back '}
Copy the code
Nine, advanced type
9.1 Cross Types
It refers to the ability to combine multiple types into one type. The identifier is &. When you specify a variable of type cross, it has all the properties of the cross type, which is the union.
interface DonInterface {
run():void;
}
interface CatInterface {
jump():void;
}
// Pet merges two types, so PET must protect methods defined by both types
let pet : DonInterface & CatInterface = {
run:function(){},
jump:function(){}}Copy the code
9.2 Association Type
- Union types indicate that a value can be one of several types.
- With a vertical bar (
|
) separate each type.- One value is a union type, and we can only access members common to all types of that union type.
function getMenus(info: string | number) {
console.log(info)
}
getMenus("Test")
getMenus(2)
/ / getMenus error (false)
Copy the code
Ten, modules,
Module: defines variables, functions, classes, etc., which can only be used in its own scope. If you want to use it externally, you must export it using export.
Use the module: import the content of the module to use.
- Modules are self-declared; The relationship between the two modules is established by using imports and exports at the file level.
- A module uses the module loader to import other modules. At run time, the module loader’s job is to find and execute all of the module’s dependencies before executing the module code.
Export 10.
10.1 Export Statement
Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.
An export can rename any declaration to prevent naming conflicts, using as
# Module A file// Export interface
export interface A {
getList() : void
}
// Export variables
export const GET_METHOD = "get"
/ / derived classes
export class S implements A {
getList(): void {
console.log("Export class")}}function getQueryData() :void {
console.log("Get paging data")}// Export module variables to be renamed
export { getQueryData asGetQuery} # file Bimport {getQuery,S,A} from A ' '. / module;
// Use functions in modules
getQuery()
// The object of the class in the instance module
const a = new S();
a.getList() // Output the exported class
// Implement the A interface in the module
class Y implements A {
getList(): void {
throw new Error('Method not implemented.'); }}Copy the code
10.2 Using combined Modules
Usually a large module is composed of several sub-modules. Then we can import multiple submodules in a large module.
Format: export * from “module”
Use composite modules: import * as rename variables from ‘composite module path’
C # module// Export variables
export const GET_METHOD = "get"
Copy the code
# module Bexport const str: string = "B module"
export function getContent() :void{
console.log("I am the contents of module B")}Copy the code
# Combine modulesconst res : object = {
code: 200.message: "Request successful"
}
export function getRes() :void {
console.log(res)} # Export submodulesexport * from "./modulesC"
export * from "./moduleB"
Copy the code
10.3 Using Combined Modules
import * as T from "./modulesA";
// in C module
console.log(T.GET_METHOD)
// The contents of the B module
console.log(T.str) / / B module
T.getContent() // I am the content of module B
// The contents of module A
T.getRes() //{code: 200, message: 'request successful'}
Copy the code
10.4 Default Export
Each module can have a default export. The default export uses the default keyword tag; And a module can only have one default export.
# moduleexport interface K {
name:string;
birth:string;
}
export default class Student implements K {
name: string;
birth: string;
constructor(name:string,birth:string){
this.name = name;
this.birth = birth;
}
getStudentInfo(){
console.log(this.name+this.birth)
}
}
Copy the code
# file Aimport D,{K} from './modulesD'
// Use the default export
const d = new D('Ming'.'1998')
d.getStudentInfo()
// The parameter type is interface K
function getMessage(obj: K) :void {
console.log(obj)
}
let obj = {
name:"Little red".birth: "1998"
}
getMessage(obj);
Copy the code
10.5 Export = import = require()
Both the CommonJS and AMD environments have an exports variable that contains all the exported content of a module.
CommonJS and AMD exports can both be assigned an object
Exports and export default use the same, but export Default syntax is not compatible with CommonJS and AMD exports.
To achieve this in TypeScript, we write:
Export = exports
Import: import module = require(“module”)
# module// Export by default
export = class Mongodbs{
host:string;
user:string;
password:string;
port:number;
databaseName:string;
constructor(host:string,user:string,password:string,port:number,databaseName:string) {
this.host = host;
this.user = user;
this.password = password;
this.port = port;
this.databaseName = databaseName
}
query(table:string){
console.log(`select * from ${table}`)}}Copy the code
# Use modulesimport MogoDb = require("./modulesE")
const mogodb = new MogoDb('1270.0.1'.'admin'.'123456'.3006.'TypeScript')
mogodb.query('Vue') //select * from Vue
Copy the code
Namespaces
- define
- “Internal modules” are called “namespaces”
- External modules are called modules
- role
- Reduce naming conflicts and organize code into a single space for easy access.
- Use the format
- through
Namespace Space name {}
, through the insideexport
Export to use internal members
namespace XiaoXin {
export interface GetData{
name: string;
price: number;
getInfo(obj:object):any;
}
export interface GetMessage {
code: number;
message: string;
}
export class Book implements GetData{
name: string;
price: number;
constructor(name:string,price:number){
this.name = name;
this.price = price
}
getInfo(obj: object) {
throw new Error("Method not implemented.");
}
buyBook(obj: GetMessage) {
console.log(obj)
}
}
}
const fontEnd = new XiaoXin.Book("Front-end Development Manual".99)
var obj = {
code: 200.message:"Purchase successful"
}
fontEnd.buyBook(obj) //{code: 200, message: 'purchase successful'}
function test(obj:XiaoXin.GetMessage){
console.log(obj)
}
test(obj) //{code: 200, message: 'purchase successful'}
Copy the code
11.1 Splitting namespaces
As the application gets bigger and bigger, we need to separate the code into different files for easy maintenance.
We can split a namespace file into multiple files, but they still use the same namespace name, and each file depends on each other. However, the namespace file must be introduced at the beginning of the file.
# root namespace namespace School {export const schoolName = "Tsinghua University"
}
Copy the code
# subnamespaces1
/// <reference path="MS1.ts" />
namespace School{
export class Teacher {
faculty:string;
name:string;
age:number;
constructor(faculty:string,name:string,age:number){
this.faculty = faculty;
this.name = name;
this.age = age
}
getInfo(){
console.log(`The ${this.name}forThe ${this.faculty}, the age ofThe ${this.age}`)}getSchool(schoole:string){
console.log(`The ${this.name}The teacher works in${schoole}`)}}}Copy the code
# subnamespaces2
///
namespace School{
export class Student{
name:string;
age:number;
hobby:string;
constructor(name:string,age:number,hobby:string) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
getInfo(){
console.log(`The ${this.name}Is a student, age isThe ${this.age}, the hobby isThe ${this.hobby}`)}}}Copy the code
Import the namespace using the merged namespace/// <reference path="MS1.ts" />
/// <reference path="MS2.ts" />
/// <reference path="MS4.ts" />
let teacher = new School.Teacher('Computer Professor'.'Dr. Chang'.34);
teacher.getInfo() // Dr. Zhang is a computer professor at the age of 34
teacher.getSchool(School.schoolName) // Dr. Zhang works in Tsinghua University
let students = new School.Student('Joe'.17.'play LOL');
students.getInfo() // Zhang SAN is a student. He is 17 years old. His hobby is playing LOL
Copy the code
Compile the namespace file
TSC --outFile sample.js test.ts Will compile to multiple JS files, TSC --outFile sample.js validation.ts lettersonlyValidator.ts zipcodeValidator.ts test.tsCopy the code
Decorator
A decorator is a special type of declaration that can be attached to class declarations, methods, accessors, attributes, and parameters of class methods to extend the behavior of a class.
Since the introduction of classes in ES2015, code has become extremely complex and inelegant when it comes to sharing or extending methods or behaviors across multiple different classes, which is an important reason decorators were proposed.
12.1 Classification of modifiers
- Class decorator
- Attribute decorator
- Method decorator
- Parameter decorator
Modifiers written:1.Plain modifiers (no arguments)2.Decorator factory (pass parameters)Copy the code
Class 12.2 Decorators
A class decorator expression is called at run time as a function, with the constructor of the class as its only argument.
Usage scenario: Applies to class constructors and can be used to monitor, modify, or replace class definitions.
const extension = (constructor: Function) :any= > {constructor.prototype.coreHour10:00-15:00 '='constructor.prototype.meeting = () = > {console.log('Reload: Daily Meeting! ');
}
}
@extension
class Employee { public name! : string public department! : stringconstructor(name: string, department: string) {
this.name = name
this.department = department
}
meeting() {
console.log('Every Monday! ')}}let e: any = new Employee('decorator'.'test')
console.log(e) //Employee {name: 'decorator ', department:' test '}
console.log(e.coreHour) / / 10:00-15:00
e.meeting() // reload: Daily meeting!
Copy the code
12.3 Class attribute decorators
Decorator expressions on class attributes are called as functions at runtime, passing in the following three parameters: Target, name, descriptor:
target
Class constructor for static members, class prototype object for instance membersname
: Member namedescriptor
: Attribute descriptor for a memberExecution order: When a function with a decorator is called, the decorator is executed before the function.
Modify the value of writable in the data descriptor:
function readonly(value: boolean){
return function(target:any,name:string,descriptor:PropertyDescriptor) {
descriptor.writable = value
}
}
class Student{
name:string;
school:string = 'Social University'
constructor(name:string) {
this.name = name
}
@readonly(false)
getDataInfo(){
console.log(`The ${this.name}Graduated from theThe ${this.school}`)}}let sss = new Student('Little Leo')
// Error reported, can only be read, cannot modify
// sss.getDataInfo = () => {
// console.log(" Test changes ")
// }
sss.getDataInfo()
Copy the code
13. TS + Vue environment construction
13.1 upgrade Vue – cli
1.Uninstall the old version NPM uninstall -g@vue /cli #or YARNglobal remove @vue/cli
2.Install NPM install -g@vue /cli # OR YARNglobal add @vue/cli
Copy the code
13.2 Creating a Project
Vue create projectname the projectname must be lowercaseCopy the code
13.3 An error occurs when Closing a Variable
Open package.json and modify the rules content as follows:"rules": {
"no-unused-vars": 0} This closesCopy the code
Selected articles
1. Vue routing menu access/button access control permissions 2. Vue | routing guard interview, often 3. Vue components communication way of 8 kinds of 4. Vue Axios encapsulated in management 5. 15 high-frequency check 20 】 【 WeChat applet interview questions
More exciting articles on the home page
The last
If there is any error in this article, welcome code friends in the comment area, if you help, welcome to like and attention ~~~