当前位置:网站首页>Typescript hands-on tutorial, easy to understand
Typescript hands-on tutorial, easy to understand
2022-07-05 08:37:00 【Thetimezipsby】
TypeScript Hands on Tutorial , Simple and easy to understand
brief introduction
TypeScript ( abbreviation ts) yes JavaScript One of the Superset , Mainly provides Type system and Yes ES6 Support for , It consists of Microsoft Development
Superset : in other words typescript Yes javascript There are no functions to enhance javascript
preparation
- install ( stay node In the environment )
npm i -g typescript or yarn global add typescript
- Check if the installation is successful
tsc -v Be careful :tsc Only after installation typescript Only then
workflow
because ts Code cannot run in the browser , So I wrote ts Code (Code.ts) from ts The compiler tsc Compile the code (Code.ts) After successful compilation, changes will be automatically created ts The corresponding js Code (Code.js)
JavaScript and TypeScript The difference between
- JavaScript: Explain and execute , Errors can only be found when running
- TypeScript: Compile and then execute , When you write, you will find mistakes (ts Not directly , You need to compile it into js )
ts The benefits of
It is conducive to standardizing our code 、 The code compilation phase can better detect errors 、 Strong type language
Entry must
Type notes
Is to add type constraints to variables , You can display and mark unexpected behavior in your code , This reduces the possibility of errors
Format :let Variable name : type = Initial value
example :let name:string = ‘ Zhang San ’
It is known that js Original type :
- The original type :string、number、boolean、null、undefined、symbol
- object type :object( Include , Array 、 object 、 Functions and other objects )
ts New type :tuple( Tuples )、enum( enumeration )、void、never、any、unknown、 Joint type 、 Literal type
usage
- Original type
// String type let myName: string = ' Zhang San ' // value type let age: number = 18 // Boolean type let isLoading: boolean = false // undefined let un: undefined = undefined // null let timer: null = null // symbol let uniKey: symbol = Symbol() // Array let array1: number[] = [1,2,3,4,5] //or let array2: Array<number> = [1,2,3,4,5] // object let obj: { name:string, age:number} = { name: ' Zhang San ', age: 18} // function let fun: (num1: number, num2: number) => number = function (num1: number, num2: number) { return num1 + num2; } console.log(fun(1, 2)); // 3 // Notice what type follows the colon , The value must be of what type , Otherwise, the compilation will report relevant errors ↓ // Type 'string' is not assignable to type 'number'.
- New type
tuple( Tuples )
It specifies the number of elements
It specifies the data type corresponding to a specific indexlet person: [number,string] = [1, ' Zhang San ']
enum( enumeration )
Using enumeration, we can define some numeric constants with names . Enumeration through enum Keyword definition .// Define a color enumeration class enum Color{ red, green, blue, } // Use let color = Color.red; console.log(color) // 0 // Be careful : The corresponding value in the enumeration defaults from 0 Start by analogy // Modify its value enum Color2{ red = 'red', green = 10, blue = 'blue' }
void
Usually used for function return value , Defining a function does not return anything , It can be considered as returning void
You can use void There are several situations :- Function didn't write return
- Only written. return, No specific return value
- return Yes. undefined
// If you don't write anything , here ,add The return value type of the function is : void const add = () => { } // If return Then I don't write anything , here ,add The return value type of the function is : void const add2 = () => { return } const add3 = (): void => { // here , Back to undefined yes JS A value of return undefined } // This way of writing is to explicitly specify that the return value type of the function is void, Same as the return value type not specified above const add4 = (): void => { }
never
It is usually applied to the return value of a function , Function as Not finished The return value of the time-varying function is never// Indicates that there will never be a return result function throwError(message:string, errorCode:number): never { throw { message, errorCode } }
any
Represents any type of , To declare that any The value of a variable of type can be of any typelet n: any; // Represents the variable n The value of can be of any type n = 123; n = '123'; n = true; // ...
unknown
Represents a value of unknown type , It can also be any typelet n: unknown; // Represents the variable n The value of can be of any type n = 123; n = '123'; n = true; // ...
expand 》》》
any、unknown difference ?
any Variables of type can be directly assigned to other variables
unknown Variables of type cannot be assigned directly to other variableslet a:any a= 123; a= 'object' let b: string b = a // ok let c: unknown; c = 123 c = '123' let d: number; d = c // Type 'unknown' is not assignable to type 'number'.
Joint type
demand : How to define a variable can be string It can also be number type ? This is the time , What we have learned before can no longer meet our needs , You need to use a new type - Joint type .let a: number | string; // Variable a You can write two types a = 123; a = '123'; a = true; // Report errors Type 'boolean' is not assignable to type 'string | number'.
Be careful : There can be more than one type after the colon use | Vertical line segmentation ; for example :let b: number | string | null | …;
A type consisting of two or more other types , The representation can be any of these types . Do not mix js Medium || Mix it upLiteral type
stay TypeScript in , Literals can not only represent values , It can also represent the type , The so-called literal type .TypeScript Support 3 Two literal types : String literal type 、 Number literal type 、 Boolean literal type . The literal amount of the corresponding string 、 Number literal quantity 、 Boolean literals have the same literal type as their values .
To put it bluntly, the type of a variable is one or more fixed values, which is the literal typelet str: 'hello world' = 'hello world'; // It means that we should str The value must be hello world let num: 996 = 996; // It means that we should num The value must be 996 let bool: true = true; // It means that we should bool The value must be true // Use with union type let age: 18 | 20 | 25 | 30; // age The value of must be One of the types after the colon age = 18; //ok age = 60;// Report errors Type '60' is not assignable to type '18 | 20 | 25 | 30'.
Types of assertions
Just tell the compiler , I know what type this value is , Also know what you are doing
Format : 1. < type > Variable name
2. Variable name as type
for example :
// Returns the length of a number or string
function getString(val: string | number): number {
// here ts Type derivation is unknown val yes string still number, You need to specify this val The type at this point is string
if ((<string>val).length) {
// Use the second assertion format
return (val as string).length;
} else {
// Now explain val The type of number
return val.toString().length;
}
}
console.log(getString(123)); // 3
console.log(getString("1234")); // 4
Type the alias
When we define types , Sometimes self-defined type names are often very long , At this time, you need to define an alias , Easy to write .
Format :type Alias = type
type s = string // Definition
const str1:s = 'abc' // Use
const str2:string = 'abc'
effect :
- Alias a type
- Defines a new type
Use scenarios : Alias complex types , such as : Multiple union types
type NewType = string | number
let a: NewType = 1
let b: NewType = '1'
function
and JavaScript equally ,TypeScript Function can create a function with a name 、 Arrow functions and anonymous functions are self executing 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
// Ordinary function
function Function name ( Shape parameter 1: type = The default value is , Shape parameter 2: type = The default value is ,...): return type {
}
// Declarative actual writing :
function add(num1: number, num2: number): number {
return num1 + num2
}
// Arrow function
const Function name ( Shape parameter 1: type = The default value is , Shape parameter 2: type = The default value is , ...): return type => {
}
const add2 = (a: number =100, b: number = 100): number =>{
return a + b
}
// Be careful : The return value type of the arrow function should be written after the parameter parentheses
function - Optional parameters
When using a function to implement a function , Parameters can be passed or not .
for example : Array of slice Method , Sure slice() It's fine too slice(1) just so so slice(1, 3) Then you can define optional parameters grammar :
function slice (a?: number, b?: number) {
// ? Follow the parameter name , Represents an optional parameter
// Be careful : Optional parameters can only be used in Must be after the parameter
// If the optional parameter is in front of the required parameter , Will report a mistake
console.log(111);
}
slice()
slice(1)
slice(1,2)
class
And js Class similarity of , It can be understood as the template of the object , Contains properties and methods
Format : class Class name ( Class names are capitalized )
class Greeter {
// attribute
greeting: string;
// Constructors
constructor(message: string) {
this.greeting = message;
}
// Method
greet() {
return "Hello, " + this.greeting;
}
}
// Create an object according to the constructor of the class
let greeter = new Greeter("world");
Class modifier
Access modifier
public
Declare properties and methods ( Default ) Properties can be accessed anywhere 、 Methodclass Point { public x: number; public y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } public getPosition() { return `(${ this.x}, ${ this.y})`; } } const point = new Point(1, 2) console.log(point.x) // 1 console.log(point.y) // 2 console.log(point.getPosition()) // (1, 2)
private
Declare properties and methods Privatize properties and methods The outside world cannot accessclass Parent { private age: number; constructor(age: number) { this.age = age; } } const p = new Parent(18); console.log(p); // { age: 18 } console.log(p.age); // Report errors Property 'age' is private and only accessible within class 'Parent'. console.log(Parent.age); // Report errors Property 'age' does not exist on type 'typeof Parent'. class Child extends Parent { constructor(age: number) { super(age); console.log(super.age); // Property 'age' is private and only accessible within class 'Parent' } }
protected
Declare properties and methods And private be similar , The difference is that in inheritance, the child can access the parent protectedclass Parent { protected age: number; constructor(age: number) { this.age = age; } protected getAge() { return this.age; } } const p = new Parent(18); console.log(p.age); // Report errors Property 'age' is protected and only accessible within class 'Parent' and its subclasses. console.log(Parent.age); // Report errors Property 'age' does not exist on type 'typeof Parent'. class Child extends Parent { constructor(age: number) { super(age); console.log(super.getAge()); } } new Child(19)
Read only modifier
You can use... In a classreadonly
Keyword sets the property to read-onlyclass UserInfo { readonly name: string; constructor(name: string) { this.name = name; } } const user = new UserInfo("TypeScript"); user.name = "haha"; // error Cannot assign to 'name' because it is a read-only property
Static modifier
You can use... In a classstatic
Key words will Properties or methods Set to static typeclass Parent { static age: number = 18; static getAge() { return Parent.age; } constructor() { // } } // Static types can be used directly without instantiating objects Class name . Method call console.log(Parent.age); // 18 console.log(Parent.getAge()) // 18
Class inheritance
And js The inheritance of is similar to , Inheritance is usually used to extend existing classes . After inheritance , The subclass will have all the properties and methods of the parent class
Format :class Subclass extends Parent class
// Create parent class
class Parent {
name: string;
constructor(name: string) {
this.name = name
}
getName() {
return this.name;
}
}
// Create a subclass and inherit the parent
class Child extends Parent {
// Constructors
constructor(childName: string) {
super(childName) // The value passed in when the subclass is created To the parent constructor
}
testFn() {
console.log(this.name)
console.log(this.getName());
}
}
const c = new Child(' Zhang San ');
c.testFn();
Be careful :
- In the constructor super() Constructor that represents the parent class as a method ,super As an object , In the ordinary way , Points to the prototype object of the parent class ;
- If you write a constructor in a subclass , You must call the constructor of the parent class
Accessors getters/setters
TypeScript Supported by getters/setters To intercept access to object members . It can help you effectively control access to object members .
class Demo {
// Private properties cannot be accessed by the outside world , It can be controlled by accessors
private _name: string;
private _age: number;
constructor(name: string, age: number) {
this._name = name;
this._age = age;
}
get name() {
// Execute when getting
return this._name;
}
set name(val: string) {
// Execute when modifying
this._name = val
}
}
const d = new Demo('a',10);
d.name = 'abc'
console.log(d.name)
Be careful : Only with get Without set The accessor of is automatically inferred as readonly
Interface
When an object type is used more than once , There are two ways to describe the types of objects , To achieve reuse :
- Type the alias ,type
- Interface ,interface
To put it bluntly, it is a way to restrict objects and classes
Format :
interface The interface name { attribute 1: type 1, attribute 2: type 2}
// Here we use interface Keyword to declare the interface
interface IGoodItem {
// The name of the interface ( such as , Here IPerson), Can be any legal variable name , Recommended to `I` start
name: string,
price: number,
func: ()=>string
}
// After declaring the interface , Directly use the interface name as the type of variable
const good1: IGoodItem = {
name: ' watch ',
price: 200,
func: function() {
return ' Look at the time '
}
}
const good2: IGoodItem = {
name: ' mobile phone ',
price: 2000,
func: function() {
return ' Make a phone call '
}
}
Interfaces and types The difference between interface( Interface ) and type( Type the alias ) Comparison of :
- The same thing : You can assign types to objects
- Difference :
- Interface , Only type can be specified for an object . It can inherit .
- Type the alias , You can not only specify the type for the object , It can actually be Any type Specify alias
// How to write the interface -------------
interface IPerson {
name: string,
age: number
}
const user1:IPerson = {
name: 'a',
age: 20
}
// type Writing -------------
type Person = {
name: string,
age: number
}
const user2:Person = {
name: 'b',
age: 20
}
Interface inheritance
If two interfaces have the same properties or methods , Public methods can be extracted from , Reuse through inheritance
Format :
interface Interface 2 extends Interface 1 {
attribute 1: type 1, // Interface 2 The unique type of
}
interface a {
x: number; y: number }
// Inherit a
// Use extends( Inherit ) Keyword implements the interface
interface b extends a {
z: number
}
// After inheritance ,b And then there is a All properties and methods of ( here ,b At the same time there is x、y、z Three attributes )
Generic
When the type is not clear , Variables can be used to temporarily replace , When used, specify or not specify ,ts Type inference will be made based on the value , Usually used for classes 、 Interfaces and functions ( That is, for better reuse )
Be careful : Generics can have multiple or one
Generic classes
Generics apply to classes
class Person<T>{
private _value: T;
constructor(val: T) {
this._value = val;
}
}
let p = new Person<number>(12)
Above , Means to pass a T type , stay new The specific type is passed into . among T(Type) It's a variable. Changeable , But it's usually more common to write T,T It can be understood as a placeholder , When instantiating, the incoming type fills this position
Generic interface
Generic application on interface
interface Identities<V, M> {
value: V,
message: M
}
let ident: Identities<number,string> = {
value: 123,
message: '123'
}
Generic functions
Generics are applied to functions
function id<T, U>(arg1: T, arg2: U): T {
return arg1;
}
// The corresponding type is passed in when calling , Don't pass on ts Type inference will be carried out according to the incoming parameters
console.log(id<string,number>('1',3)) // "1"
console.log(id('1',3)) // "1"
It's over here , It will be updated later vue Series related , Please keep an eye on !
Thank you for reading , If there are errors, you can leave a message in the comment area below !!!
Recommended articles
ts Nanny class course , Don't say you won't ts 了
You don't know TypeScript Generic ( Ten thousand words long text , Recommended collection )
Near the ceiling TS Type gymnastics , If you understand, you can play TS 了
TypeScript Medium never What's the use of type ?
understand TypeScript Type narrowing
边栏推荐
- Infected Tree(树形dp)
- Reasons for the insecurity of C language standard function scanf
- 猜谜语啦(9)
- U8g2 drawing
- [noi simulation] juice tree (tree DP)
- Briefly talk about the identification protocol of mobile port -bc1.2
- Example 007: copy data from one list to another list.
- 实例009:暂停一秒输出
- Meizu Bluetooth remote control temperature and humidity access homeassistant
- STM32 single chip microcomputer - external interrupt
猜你喜欢
99 multiplication table (C language)
STM32 virtualization environment of QEMU
猜谜语啦(2)
猜谜语啦(6)
EA introduction notes
Bluebridge cup internet of things basic graphic tutorial - GPIO output control LD5 on and off
Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?
STM32 lights up the 1.8-inch screen under Arduino IDE
Apaas platform of TOP10 abroad
MATLAB小技巧(28)模糊综合评价
随机推荐
Meizu Bluetooth remote control temperature and humidity access homeassistant
Example 008: 99 multiplication table
2022.7.4-----leetcode. one thousand and two hundred
Sword finger offer 09 Implementing queues with two stacks
Lori remote control commissioning record
Apaas platform of TOP10 abroad
How apaas is applied in different organizational structures
Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off
Esp8266 interrupt configuration
GEO数据库中搜索数据
Example 010: time to show
Stm32--- systick timer
实例005:三数排序 输入三个整数x,y,z,请把这三个数由小到大输出。
Sword finger offer 06 Print linked list from end to end
Arduino operation stm32
287. 寻找重复数-快慢指针
Arduino+a4988 control stepper motor
Shell script realizes the reading of serial port and the parsing of message
Run menu analysis
暑假第一周