当前位置:网站首页>Typescript learning
Typescript learning
2022-06-27 22:13:00 【Elegant pig】
1.TypeScript Introduce
TypeScript It's an open source developed by Microsoft 、 Cross platform programming language . It is JavaScript Superset , It will eventually be compiled as JavaScript Code .2012 year 10 month , Microsoft has released the first public version of TypeScript,2013 year 6 month 19 Japan , After a preview, Microsoft officially released the official version TypeScript.TypeScript The author is Anders · hejlsberg ,C# Chief architect of . It is an open source and cross platform programming language . It is designed for the development of large-scale applications , And can be compiled as JavaScript, yes JavaScript A superset of , It mainly provides the type system and pair ES6+ Support for
TypeScript Can compile pure 、 concise JavaScript Code , And it can run on any browser 、Node.js Environment and any support ECMAScript 3( Or later ) Of JavaScript In the engine , Type system allows JavaScript Developers are developing JavaScript The application uses efficient development tools and common operations such as static checking and code refactoring .
2.TypeScript install
2.1 Global installation
npm install -g typescript2.2 Check if the installation is successful , View version
tsc -V 3.TypeScript The code to compile
newly build typescript/hello.ts file , Use VSCode open
To write ts Code
console.log('hello TypeScript')3.1 Manually compile
Command line input
tsc helloworld.tsThe output is a hello.js file , This is going to ts Code compiled js Code
Then type on the command line
node hello.jsConsole output
hello TypeScriptManual compilation is when we write code every time , All need to be renewed tsc hello.ts It can only be compiled into js Code , More trouble
3.2 Automatic compilation
3.2.1 Generate tsconfig.json file
tsc --init3.2.2 modify tsconfig.json To configure
"outDir": "./js",
"strict": false3.2.3 Start the monitoring task
terminal -> Run the task -> monitor tsconfig.json4.TypeScript The base type
TypeScript Support and JavaScript Almost the same data type , In addition, some new types are added for convenience ( Such as enumeration ) We use .
4.1 String type
let str: string = 'test'4.2 Numeric type
let num: number = 124.3 null type
let n: null = null4.4 undefined type
let u: undefined = undefined4.5 Boolean type
let b:boolean = true4.6 any type ( To use less )
let a: any = ' I am a value of any type '
a = 12
a = true
a = null
a = undefined
a = () => {}
let str1: string = 'wft'
str1 = a // Don't complain ,any Type is equivalent to closing us ts Type checking , So try not to use 4.7 unknown type
// Unknown type
let unk: unknown = '12'
let str2: string = 'www'
// str2 = unk // Report errors , If there is an unknown type , We use unknow Instead of any4.8 Joint type
let unio: string | number | boolean = true
unio = '121'
unio = 104.9 An array type
let arr1: number[] = [1,2,3]
let arr2: Array<string> = ['1', '2', '3']
let arr3: any[] = [1, '2', false, null, undefined]4.10 Tuples Tuple type
Array length is fixed
let arr4:[string, number] = ['1', 2] // correct
// arr4 = ['1',2, 3] // Report errors
// arr4 = [2, '1'] // Report errors 4.11 Enumeration type
// The enumeration value defaults from 0 Start increasing in sequence
// Get the corresponding enumeration value according to the specific name
enum Flag1 {
name = 'wft',
age = 18
}
enum Flag2 {
name,
age = 18,
height
}
enum Flag3 {
name,
age,
height
}
let flag1: Flag1 = Flag1.name
let flag2: Flag2 = Flag2.height
let flag3: Flag3 = Flag3.height;
console.log(flag1, flag2, flag3); // wft 19 24.12 void type
void Type is generally used for functions that do not return a value , That is, the default return value is undefined
(function fn(): void {
console.log(' I have no return value ~~');
})()4.13 never type
This also means that there is no return value , He and void The difference is that ,void Can return , It's just not worth it (undefined), however never Is to return undefined Neither. , There can be no return at all , Generally used to throw an error
function err(): never {
throw new Error(' Throw an error ')
}4.14 Types of assertions
A type assertion is a type that can manually specify a value . This way of asserting by type is like telling the compiler :“ believe me , I know what I'm doing ”, It has no runtime impact , How to execute the code , It only works during the compilation phase , Be able to compile through . Two kinds of grammar :1. Angle bracket Syntax 2.as keyword
// Type assertions tell the compiler that ,“ believe me , I know what I'm doing ”.
// Type assertions are like type conversions in other languages , But no special data checking and deconstruction .
// It has no runtime impact , It only works during the compilation phase .
// TypeScript Will assume you , The programmer , The necessary checks have been carried out .
// Mode one : <> value
// Mode two : as keyword
function getLength(x: number | string): number {
if ((<string>x).length) {
return (x as string).length
} else {
return x.toString().length
}
}
console.log(getLength('abcd'), getLength(1234), '---->>') // 4 44.15 Type inference
TS Will infer a type when there is no specific type
There are the following 2 In this case : 1. When defining a variable, it is assigned , Infer to the corresponding type . 2. Variables are defined without assignment , Infer as any type
// When defining a variable, it is assigned , Infer to the corresponding type
let w = 110 // number type
// w = 'hahha' // Report errors
// Variables are defined without assignment , Infer as any
let wn; //any type
wn = 12
wn = '1212'5.TypeScript function
and JavaScript equally ,TypeScript Functions can create named functions and anonymous functions . You are free to choose the way that suits the application , Whether it's defining a series of API Function is still a function that is used only once .
TypeScript by JavaScript Function adds extra functionality , Let's make it easier to use
5.1 Function declaration
function add (a: number, b: number): number {
return a + b
}
add(1,2)5.2 Function expression
const add = function(a: number, b: number): number {
return a + b
}
add(1,2)5.3 Required parameters
function getInfo(name: string, age: number) {
return `${name} This year, ${age} Year old `
}
getInfo(' Xiao Wang ', 12)5.3 Optional parameters
function getInfo(name: string, age?: number) {
return age ? `${name}----${age}` : `---${name}---`
}
getInfo(' Xiao Wang ', 12)
getInfo(' I'm Xiao Wang ')5.4 Default parameters
Be careful : Optional parameters cannot be set to default values
function getInfo(name: string = ' Xiao Wang ', age: number = 20) {
return `${name} This year, ${age} Year old `
}
getInfo(' Xiao Wang ', 12)
getInfo()5.5 The remaining parameters
function myInfo(name: string, ...args: string[]) {
console.log(name, args)
}
myInfo(' Xiao Wang ', '1', '2', '3')5.6 function overloading
Function overloading refers to multiple functions of the same name with different formal parameters
5.6.1 example 1
function info(name: string): string;
function info(name: string, age: number): string
// Overloaded function signature : Is to write out all the parameters in the declaration , If optional , Use optional parameters , A variable name can use a combination of multiple types
function info(name: string, age?: number): string {
if(age) {
return `${name} This year, ${age} Year old `
} else {
return ` My name is ${name}`
}
}
console.log(info("zhangsan"));
console.log(info("lisi", 20));
// console.log(info(123));// error5.6.2 example 2
function add (x: string, y: string): string
function add (x: number, y: number): number
// Define function implementation
function add(x: string | number, y: string | number): string | number {
// In implementation, we should pay attention to strictly judge whether the types of two parameters are equal , Instead of simply writing a x + y
if (typeof x === 'string' && typeof y === 'string') {
return x + y
} else if (typeof x === 'number' && typeof y === 'number') {
return x + y
}
}
console.log(add(1, 2))
console.log(add('a', 'b'))
// console.log(add(1, 'a')) // error6. Interface
TypeScript One of the core principles of is to type check the structure of a value . We use interfaces (Interface) To define the type of object . An interface is the state of an object ( attribute ) And behavior ( Method ) The abstraction of ( describe )
Interfaces can be used to define objects ( Or class ) When it comes to limiting objects ( Or class ) Structure
All properties in an interface cannot have actual values
Interfaces only define the structure of objects , Regardless of the actual value
All methods in the interface are abstract methods
6.1 Property type interface
6.1.1 Required attributes
interface Person {
id: string,
name: string,
age: number
}
const IPerson: Person = {
id: '001',
name: 'wft',
age: 18
}6.1.2 Optional attribute
interface Person {
id: string,
name: string,
age: number,
sex?: string
}
const IPerson: Person = {
id: '001',
name: 'wft',
age: 18,
// sex: ' male ' // There can be no
}6.1.3 Read-only property
interface Person {
readonly id: string,
name: string,
age: number
}
const IPerson: Person = {
id: '001',
name: 'wft',
age: 18
}
// IPerson.id = '121212' // Do not modify the 6.1.4 Object properties
interface Info {
height: string,
}
interface Person {
id: string,
name: string,
age: number,
info: Info // object
}
const IPerson: Person = {
id: '001',
name: 'wft',
age: 18,
info: {
height: '1.88'
}
}6.1.5 arbitrarily key
interface Person {
id: string, // id Is a required attribute
[PropName: string]: any // Add whatever else you like
}
const IPerson: Person = {
id: '001',
name: 'wft',
age: 18
}6.2 Function class interface
Interfaces can describe function types ( That is, the type of the parameter and the type returned )
interface Reversal {
(str1: string, str2: string): string
}
const strReverse: Reversal = (str1: string, str2: string): string {
return (str1 + str2).split('').reverse().join('')
}
console.log(strReverse('123', '456'));6.3 Class type interface
interface Animal {
name: string,
eat(food: string): void
}
class Cat implements Animal {
name: string
constructor(name: string) {
this.name = name
}
eat(food: string): void {
console.log(`${this.name} eat ${food}`);
}
}
let cat = new Cat(' cat ')
cat.eat(' fish ')A class implements multiple interfaces :
interface Animal1 {
name: string,
eat(food: string): void
}
interface Animal2 {
age: number,
fn(str: string): void
}
class Cat implements Animal1, Animal2 {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
eat(food: string): void {
console.log(`${this.name} eat ${food}`);
}
fn(): void {
console.log(`${this.name} This year, ${this.age} Year old `);
}
}
let cat = new Cat(' cat ', 2)
cat.eat(' fish ')
cat.fn()6.4 Interface inheritance
Interfaces are the same as classes , They can also inherit from each other , This allows us to copy members from one interface to another , The interface can be more flexibly divided into reusable modules .
// Animal interface
interface Animal {
name: string,
eat(food: string): void
}
// Flying animals
interface Fly extends Animal {
wing(): void
}
class Eagle implements Fly {
name: string
constructor(name: string) {
this.name = name
}
eat(food: string): void {
console.log(`${this.name} eat ${food}`);
}
wing(): void {
console.log(' Chicken vs Eagle ');
}
}
let fly = new Eagle(' The eagle ')
fly.eat(' Chick ')
fly.wing()7. class
Objects are created by classes , adopt new keyword , When we new When , Just do it automatically class Medium constructor Method , Create an object , And changed. this Point to , Point to the created object
7.1 The basic use of classes
class C {
name: string // Omit the previous public( Default ) keyword
constructor(name:string) {
this.name = name
}
getName(): void {
console.log(` My name is ${this.name}`);
}
}
let c = new C('wft')
c.getName()7.2 Class inheritance
class C {
name: string // Omit the previous public( Default ) keyword
constructor(name:string) {
this.name = name
}
getName():void {
console.log(` My name is ${this.name}`);
}
}
class D extends C {
age: number
// Class inheritance once used constructor Then use super Method calls the constructor of the parent class
constructor(name: string, age: number) {
super(name)
this.age = age
}
getInfo(): void {
super.getName() // Calls a method of the parent class
console.log(`${this.name} This year, ${this.age} 了 `);
}
}
let d = new D('wft', 18)
d.getInfo()
d.getName()7.3 Property modifier
class AttrTest {
public name: string // Properties of public types ( Default ), Inside 、 external 、 Subclasses can access
private age: number // Private property , Can only be accessed inside a class
protected sex: string // Internally and subclasses can access 、 No access from outside
readonly id: string // Read-only property , Read only properties must be initialized in declarations or constructors
constructor() {
console.log(' Property testing ')
}
}7.4 Static attribute
The above discussion is all about instance members of classes , Properties that are initialized only when the class is instantiated
Static attributes do not need to be instantiated , It only needs static keyword , You can access directly through the class name
The same way , No more details here
class AttrTest {
static sta: string = ' I'm a static property '
constructor() {
console.log(' Property testing ')
}
}
console.log(AttrTest.sta);7.5 abstract class
An abstract class is a base class that is provided to other classes to inherit , Can't be instantiated directly
adopt abstract Keyword defines an abstract class and defines an abstract method inside an abstract class
abstract class C {
name: string // Omit the previous public( Default ) keyword
constructor(name:string) {
this.name = name
}
abstract fn(): void // Abstract methods do not contain concrete implementations and must be implemented in derived classes
getName():void {
console.log(` My name is ${this.name}`);
}
}
class D extends C {
age: number
// Class inheritance once used constructor Then use super Method calls the constructor of the parent class
constructor(name: string, age: number) {
super(name)
this.age = age
}
fn(): void { // Subclasses must implement abstract methods in the abstract parent class
console.log(' Abstract methods in a parent class ');
}
getInfo(): void {
super.getName() // Calls a method of the parent class
console.log(`${this.name} This year, ${this.age} 了 `);
}
}8. Generic
Generics are defined functions 、 Interface or class, we are not sure what type of value will be passed in , The type is not specified in advance , When used, a specific type of feature is specified
8.1 The function of generic
/**
* example 1
* @param value Not sure what type , What type we pass in is what type
* @returns Return length is 1 The inclusion of value Array of
*/
function test<T>(value: T): T[] {
return [ value ]
}
/**
* example 2
* Create a containing count individual value Array of
* @param value Not sure what type , What type we pass in is what type
* @param count Numeric type
* @returns Returns an array of unknown type
*/
function createArr<T>(value: T, count: number): T[] {
const arr:T[] = []
for(let i = 0; i < count; i++) {
arr.push(value)
}
return arr
}
console.log(createArr('push', 5))// [ 'push', 'push', 'push', 'push', 'push' ]8.2 Functions with multiple generic parameters
/**
* example 3
* Functions with multiple generic parameters
* @param value1 Unknown type
* @param value2 Unknown type
* @returns Return length is 2 Tuples of indeterminate types of
*/
function test<K, V>(value1: K, value2: V): [K, V] {
return [value1, value2]
}
console.log(test(() => 1, 1)); //[ [Function], 1 ]8.3 Generic interface
interface IFn<T> {
(value: T): T
}
const fn: IFn<string> = (value: string) => value8.4 Generic classes
class TTest<T> {
name: T
age: T
fn: (a: T, b:T) => T
constructor(name: T, age: T) {
this.name = name
this.age = age
}
}
// We pass in generic types when instantiating , Is to specify a type for a generic type
let o = new TTest<string>('wft', '12')
o.fn = function(a, b) {
return a + b
}Learning reference :
边栏推荐
- 6G显卡显存不足出现CUDA Error:out of memory解决办法
- Gbase 8A OLAP analysis function cume_ Example of dist
- GBase 8a OLAP分析函数cume_dist的使用样例
- QT large file generation MD5 check code
- 畅游动态规划之区间DP
- Golang uses regularity to match substring functions
- How to design an elegant caching function
- gomock mockgen : unknown embedded interface
- [sword offer ii] sword finger offer II 029 Sorted circular linked list
- .NET学习笔记(五)----Lambda、Linq、匿名类(var)、扩展方法
猜你喜欢

管理系统-ITclub(上)
![[leetcode] dynamic programming solution partition array i[red fox]](/img/b2/df87c3138c28e83a8a58f80b2938b8.png)
[leetcode] dynamic programming solution partition array i[red fox]
![[leetcode] dynamic programming solution partition array ii[arctic fox]](/img/a1/4644206db3e14c81f9f64e4da046bf.png)
[leetcode] dynamic programming solution partition array ii[arctic fox]

Login credentials (cookie+session and token token)

开源技术交流丨一站式全自动化运维管家ChengYing入门介绍

读写分离-Mysql的主从复制

Use Fiddler to simulate weak network test (2g/3g)

Ellipsis after SQLite3 statement Solutions for

Codeforces Round #723 (Div. 2)

Go from introduction to practice -- definition and implementation of behavior (notes)
随机推荐
我想我要开始写我自己的博客了。
Example of using gbase 8A OLAP function group by grouping sets
Management system itclub (Part 1)
[MySQL practice] query statement demonstration
管理系統-ITclub(下)
Common problems encountered by burp Suite
The problem of minimum modification cost in two-dimensional array [conversion question + shortest path] (dijkstra+01bfs)
crontab定时任务常用命令
Software test automation test -- interface test from entry to proficiency, learn a little every day
[LeetCode]508. The most frequent subtree elements and
清华大学教授:软件测试已经走入一个误区——“非代码不可”
【Redis】零基础十分钟学会Redis
CUDA error:out of memory caused by insufficient video memory of 6G graphics card
Ellipsis after SQLite3 statement Solutions for
Gbase 8A OLAP analysis function cume_ Example of dist
MONTHS_BETWEEN函数使用
Matlab finds the position of a row or column in the matrix
Selenium上传文件有多少种方式?不信你有我全!
正则表达式
Use Fiddler to simulate weak network test (2g/3g)