当前位置:网站首页>Get started with typescript
Get started with typescript
2022-07-06 13:49:00 【Ling Xiaoding】
TypeScript Quick start
Tips : This article is based on B Standing in Silicon Valley TypeScript course ( Mr. Li Lichao TS new course ) Arrangement
B Station video guidance : Silicon Valley TypeScript course ( Mr. Li Lichao TS new course )
List of articles
Preface
- TypeScript yes JavaScript Superset .
- It's right JS It has been extended , towards JS The concept of type is introduced in , And added many new features .
- TS The code needs to be compiled into JS, And then to JS The parser executes .
- TS Fully compatible with JS, In other words , Any JS Code can be used directly as TS Use .
- Compare with JS for ,TS With static types , More strict grammar , More powerful features ;TS You can check your code before it executes , Reduces the probability of runtime exceptions ;TS The code can be compiled into any version of JS Code , It can effectively solve different problems JS Compatibility of operating environment ; Same function ,TS The amount of code is greater than JS, But because of TS The code structure of is clearer , Variable types are more explicit , In later code maintenance TS But far better than JS.
Tips : The following is the main body of this article , The following cases can be used for reference
One 、TypeScript Development environment construction
TypeScript
The premise of use is to installNode.js
( Please make sure that the installation is complete )- Use
npm
Global installationtypescript
npm i -g typescript
- Create a
ts
file , Usetsc
Yests
File for compilation
- Go to the command line
- Get into ts File directory
- Carry out orders :
tsc xxx.ts
Two 、 Basic types
2.1 Type declaration
- The type declaration is
TS
A very important feature - Type declarations allow you to specify
TS
Medium variable ( Parameters 、 Shape parameter ) The type of - After specifying the type , When assigning a value to a variable ,
TS
The compiler will automatically check whether the value conforms to the type declaration , If yes, the value is assigned , Otherwise, the report will be wrong - In short , The type declaration sets the type... For the variable , So that variables can only store certain types of values
- grammar :
let Variable : type ;
let Variable : type = value ;
function fn( Parameters : type , Parameters : type ): type {
...
}
2.2 Automatic type determination
TS
Have automatic type judgment mechanism- When the declaration and assignment of variables are carried out at the same time ,
TS
The compiler automatically determines the type of the variable - So if you declare and assign variables at the same time , You can omit the type declaration
2.3 type
type | Example | describe |
---|---|---|
number | 1, -33, 2.5 | Arbitrary number |
string | ‘hi’, “hi”, hi | Any string |
boolean | true、false | Boolean value true or false |
Literal | Its own | The value of the limiting variable is the literal value |
any | * | Any type |
unknown | * | Type safe any |
void | Null value (undefined) | No value ( or undefined) |
never | No value | Cannot be any value |
object | {name:‘ The Monkey King ’} | Any of the JS object |
array | [1,2,3] | arbitrarily JS Array |
tuple | [4,5] | Yuan Zu ,TS New type , Fixed length array |
enum | enum{A, B} | enumeration ,TS New type in |
number
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
let big: bigint = 100n;
boolean
let isDone: boolean = false;
string
let color: string = "blue";
color = 'red';
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${
fullName}. I'll be ${
age + 1} years old next month.`;
Literal
- You can also use literals to specify the type of variable , The value range of the variable can be determined by literal quantity
- have access to | To connect multiple types ( Joint type )
let color: 'red' | 'blue' | 'black';
let num: 1 | 2 | 3 | 4 | 5;
any
any
Represents any type , A variable is set to typeany
After that, it is equivalent to turning off the variableTS
Type detection of- Use
TS
when , Not recommendedany
type
let d: any = 4;
d = 'hello';
d = true;
- Declare a variable if you don't specify a type , be TS The parser will automatically determine that the type of the variable is
any
( implicitany
)
let d;
d = 10;
d = 'hello';
d = true;
unknown
unknown
Represents a value of unknown typeunknown
It's actually a type safe anyunknown
Variable of type , Cannot be assigned directly to other variables
let notSure: unknown = 4;
notSure = 'hello';
void
void
It is used to express empty , Take functions for example , A function that has no return value
let unusable: void = undefined;
function fn(): void{
}
never
never
Indicates that the result will never be returned
function error(message: string): never {
throw new Error(message);
}
object
object
It means ajs
object
// {} Used to specify which attributes can be included in an object
// grammar :{ Property name : Property value , Property name : Property value }
// Add... After the attribute name ?, Indicates that the property is optional
let b: {
name: string, age?: number};
b = {
name: ' The Monkey King ', age: 18};
// [propName: string]: any Represents any type of property
let c: {
name: string, [propName: string]: any};
c = {
name: ' Pig eight quit ', age: 18, gender: ' male '};
let obj: object = {
};
array
/* * Array type declaration : * type [] * Array< type > * */
// string[] Represents an array of strings
let e: string[];
e = ['a', 'b', 'c'];
// number[] Represents a numeric value
let f: number[];
let g: Array<number>;
g = [1, 2, 3];
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
tuple
- Tuples , Tuples are fixed length arrays
/* * Tuples , Tuples are fixed length arrays * grammar :[ type , type , type ] * */
let x: [string, number];
x = ["hello", 10];
enum enumeration
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green,
Blue,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green = 2,
Blue = 4,
}
let c: Color = Color.Green;
// & Indicates simultaneous
let j: {
name: string } & {
age: number };
j = {
name: ' The Monkey King ', age: 18};
Types of assertions
- In some cases , The type of variable is very clear to us , however TS The compiler doesn't know , here , You can tell the compiler the type of a variable through type assertions , There are two forms of assertion :
/* - grammar : - Variable as type - < type > Variable - */
s = e as string;
s = <string>e;
- The first one is
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
- The second kind
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;
Alias for type
type myType = 1 | 2 | 3 | 4 | 5;
let k: myType;
let l: myType;
let m: myType;
k = 2;
3、 ... and 、 object-oriented
3.1 class (class)
for instance : Can pass Person
Class to create human objects , adopt Dog
Class to create a dog object , adopt Car
Class to create an object for the car , Different classes can be used to create different objects .
Defining classes :
class Class name {
Property name : type ;
constructor( Parameters : type ){
this. Property name = Parameters ;
}
Method name (){
....
}
}
Example :
Defining classes
class Person{
name: string;
age: number;
constructor(name: string, age: number){
this.name = name;
this.age = age;
}
sayHello(){
console.log(` Hello everyone , I am a ${
this.name}`);
}
}
Use class
const p = new Person(' The Monkey King ', 18);
p.sayHello();
3.2 Object oriented features
3.2.1 keyword
- encapsulation
- Objects are essentially containers for properties and methods , Its main function is to store properties and methods , This is called encapsulation
- By default , The properties of an object can be modified arbitrarily , To ensure the security of data , stay TS You can set the permissions of attributes in
- Read-only property (
readonly
):
If you add a... When declaring a propertyreadonly
, Then the attribute becomes a read-only attribute and cannot be modified - TS Attributes in have three modifiers :
1.public
( The default value is ), Can be in the class 、 Modify in subclasses and objects
2.protected
, Can be in the class 、 Modify in subclass
3.private
, You can modify... In a class - Example :
- public
class Person{
public name: string; // Writing or not writing anything is public
public age: number;
constructor(name: string, age: number){
this.name = name; // You can modify... In a class
this.age = age;
}
sayHello(){
console.log(` Hello everyone , I am a ${
this.name}`);
}
}
class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; // Subclasses can be modified
}
}
const p = new Person(' The Monkey King ', 18);
p.name = ' Pig eight quit ';// Can be modified by objects
- protected
class Person{
protected name: string;
protected age: number;
constructor(name: string, age: number){
this.name = name; // You can modify
this.age = age;
}
sayHello(){
console.log(` Hello everyone , I am a ${
this.name}`);
}
}
class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; // Subclasses can be modified
}
}
const p = new Person(' The Monkey King ', 18);
p.name = ' Pig eight quit ';// Do not modify
- private
class Person{
private name: string;
private age: number;
constructor(name: string, age: number){
this.name = name; // You can modify
this.age = age;
}
sayHello(){
console.log(` Hello everyone , I am a ${
this.name}`);
}
}
class Employee extends Person{
constructor(name: string, age: number){
super(name, age);
this.name = name; // Cannot modify in subclass
}
}
const p = new Person(' The Monkey King ', 18);
p.name = ' Pig eight quit ';// Do not modify
Attribute accessor
- For some properties that do not want to be modified arbitrarily , You can set it to
private
- Set it directly to
private
Will result in the inability to modify its properties through the object - We can define a set of reads in the class 、 How to set properties , The property read or set to the property is called the accessor of the property
- The method of reading properties is called
setter
Method , The method of setting properties is calledgetter
Method - Example :
class Person{
private _name: string;
constructor(name: string){
this._name = name;
}
get name(){
return this._name;
}
set name(name: string){
this._name = name;
}
}
const p1 = new Person(' The Monkey King ');
console.log(p1.name); // adopt getter Read name attribute
p1.name = ' Pig eight quit '; // adopt setter modify name attribute
Static attribute
- Static attribute ( Method ), Also known as class properties . There is no need to create an instance to use static properties , Through the class, you can directly use
- Static attribute ( Method ) Use
static
start - Example :
class Tools{
static PI = 3.1415926;
static sum(num1: number, num2: number){
return num1 + num2
}
}
console.log(Tools.PI);
console.log(Tools.sum(123, 456));
this
In class , Use this Represents the current object
3.2.2 Constructors
constructor
It's called a constructor- The constructor is called when the object is created
class Dog{
name: string;
age: number;
// constructor It's called a constructor
// The constructor is called when the object is created
constructor(name: string, age: number) {
// In the instance method ,this It means the current instance
// In the constructor, the current object is the newly created object
// Can pass this Add properties to the new object
this.name = name;
this.age = age;
}
bark(){
// alert(' Wang Wang Wang !');
// In the method, you can use this To represent the object of the current calling method
console.log(this.name);
}
}
const dog = new Dog(' Little black ', 4);
const dog2 = new Dog(' The small white ', 2);
// console.log(dog);
// console.log(dog2);
dog2.bark();
3.2.3 Inherit extends
(function (){
// Define a Animal class
class Animal{
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello(){
console.log(' Animals are barking ~');
}
}
/* * Dog extends Animal * - here ,Animal It's called the parent class ,Dog It's called a subclass * - After using inheritance , The subclass will have all the methods and properties of the parent class * - Through inheritance, you can write code common to multiple classes in a parent class , * In this way, you only need to write once to make all subclasses have the properties and methods in the parent class at the same time * If you want to add some properties or methods in the subclass that are not in the parent class, just add them directly * - If the same method as the parent class is added to the child class , The subclass method will override the parent method * This subclass covers the form of the parent method , We call it method rewriting * * */
// Define a class that represents dogs
// send Dog Class inheritance Animal class
class Dog extends Animal{
run(){
console.log(`${
this.name} Running ~~~`);
}
sayHello() {
console.log(' Wang Wang Wang Wang !');
}
}
// Define a class that represents a cat
// send Cat Class inheritance Animal class
class Cat extends Animal{
sayHello() {
console.log(' Meow meow !');
}
}
const dog = new Dog(' Wangcai ', 5);
const cat = new Cat(' Mimi ', 3);
console.log(dog);
dog.sayHello();
dog.run();
console.log(cat);
cat.sayHello();
})();
3.2.4 super keyword
(function () {
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sayHello() {
console.log(' Animals are barking ~');
}
}
class Dog extends Animal{
age: number;
constructor(name: string, age: number) {
// If you write a constructor in a subclass , In the subclass constructor, the constructor of the parent class must be called
super(name); // Call the constructor of the parent class
this.age = age;
}
sayHello() {
// In the method of a class super Represents the parent of the current class
//super.sayHello();
console.log(' Wang Wang Wang Wang !');
}
}
const dog = new Dog(' Wangcai ', 3);
dog.sayHello();
})();
3.2.5 abstract class
- With
abstract
The starting class is an abstract class
(function () {
/* * With abstract The starting class is an abstract class , * Abstract classes are not very different from other classes , It just can't be used to create objects * Abstract classes are classes that are specifically used to be inherited * * Abstract methods can be added to abstract classes * */
abstract class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
// Define an abstract method
// Use of abstract methods abstract start , There is no method body
// Abstract methods can only be defined in abstract classes , Subclasses must override abstract methods
abstract sayHello():void;
}
class Dog extends Animal{
sayHello() {
console.log(' Wang Wang Wang Wang !');
}
}
class Cat extends Animal{
sayHello() {
console.log(' Meow meow !');
}
}
const dog = new Dog(' Wangcai ');
dog.sayHello();
})();
3.2.6 Encapsulation of attributes
(function (){
// Define a class that represents people
class Person{
// TS You can add a modifier to an attribute before it
/* * public Decorated properties can be accessed anywhere ( modify ) The default value is * private Private property , Private properties can only be accessed inside a class ( modify ) * - Private properties can be accessed externally by adding methods to the class * protected Included properties , Can only be accessed in the current class and subclasses of the current class ( modify ) * * */
private _name: string;
private _age: number;
constructor(name: string, age: number) {
this._name = name;
this._age = age;
}
/* * getter Method is used to read properties * setter Method to set properties * - They are called property accessors * */
// Define methods , Used to obtain name attribute
// getName(){
// return this._name;
// }
//
// // Define methods , Used to set name attribute
// setName(value: string){
// this._name = value;
// }
//
// getAge(){
// return this._age;
// }
//
// setAge(value: number){
// // Judge whether age is legal
// if(value >= 0){
// this._age = value;
// }
// }
// TS Set in getter Method of method
get name(){
// console.log('get name() Yes !!');
return this._name;
}
set name(value){
this._name = value;
}
get age(){
return this._age;
}
set age(value){
if(value >= 0){
this._age = value
}
}
}
const per = new Person(' The Monkey King ', 18);
/* * Now the properties are set in the object , Properties can be modified arbitrarily , * Properties can be modified arbitrarily, which will make the data in the object very unsafe * */
// per.setName(' Pig eight quit ');
// per.setAge(-33);
per.name = ' Pig eight quit ';
per.age = -33;
// console.log(per);
class A{
protected num: number;
constructor(num: number) {
this.num = num;
}
}
class B extends A{
test(){
console.log(this.num);
}
}
const b = new B(123);
// b.num = 33;
/* class C{ name: string; age: number // You can define properties directly in the constructor constructor(name: string, age: number) { this.name = name; this.age = age; } }*/
class C{
// You can define properties directly in the constructor
constructor(public name: string, public age: number) {
}
}
const c = new C('xxx', 111);
console.log(c);
})();
3.3 Interface (Interface)
Interfaces act like abstract classes , The difference is that all methods and properties in the interface have no real values , In other words, all methods in the interface are abstract methods . Interface is mainly responsible for defining the structure of a class , Interface can be used to restrict the interface of an object , An object can match an interface only if it contains all the properties and methods defined in the interface . meanwhile , You can let a class implement the interface , When implementing the interface, all properties in the interface should be protected in the class .
Example ( Check the object type ):
interface Person{
name: string;
sayHello():void;
}
function fn(per: Person){
per.sayHello();
}
fn({
name:' The Monkey King ', sayHello() {
console.log(`Hello, I am a ${
this.name}`)}});
Example ( Realization )
interface Person{
name: string;
sayHello():void;
}
class Student implements Person{
constructor(public name: string) {
}
sayHello() {
console.log(' Hello everyone , I am a '+this.name);
}
}
Example :
(function () {
// Describe the type of an object
type myType = {
name: string,
age: number
};
/* * Interface is used to define a class structure , It is used to define which properties and methods should be included in a class * At the same time, interfaces can also be used as type declarations * */
interface myInterface {
name: string;
age: number;
}
interface myInterface {
gender: string;
}
// const obj: myInterface = {
// name: 'sss',
// age: 111,
// gender: ' male '
// };
/* * Interfaces can limit the structure of a class when defining it , * All properties in the 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 * * */
interface myInter{
name: string;
sayHello():void;
}
/* * When defining a class , You can make a class implement an interface , * To implement an interface is to make the class meet the requirements of the interface * */
class MyClass implements myInter{
name: string;
constructor(name: string) {
this.name = name;
}
sayHello(){
console.log(' Hello everyone ~~');
}
}
})();
3.4 Generic (Generic)
When defining a function or class , In some cases, it is not possible to determine the specific type to be used ( Return value 、 Parameters 、 The type of the property cannot be determined ), At this point, generics can work .
for instance :
In this case ,test The function has an argument of uncertain type , But when it can be determined, the type of the return value and the type of the parameter are the same , Because the type is uncertain, both the parameter and the return value use any, But obviously this is not appropriate , use first any Will close TS Type check of , Secondly, this setting cannot reflect that the parameter and return value are of the same type
function test(arg: any): any{
return arg;
}
Use generics : Here is generics ,T We named this type ( Not necessarily T), Once the generics are set, they can be used in functions T To represent the type . So generics are actually easy to understand , It means a certain type .
function test<T>(arg: T): T{
return arg;
}
So how to use the above function ?
- Mode one ( Use it directly ):
When in use, you can directly pass parameters , The type will be determined by TS Automatically infer , But sometimes when the compiler cannot automatically infer, you need to use the following method
test(10)
- Mode two ( Specify the type ):
You can also specify generics manually after a function
test<number>(10)
Multiple generics can be specified at the same time , Generics are separated by commas :
When using generics , You can use generics as an ordinary class
function test<T, K>(a: T, b: K): K{
return b;
}
test<number, string>(10, "hello");
besides , You can also constrain the scope of generics
Use T extends MyInter For generics T Must be MyInter Subclasses of , You don't have to use interface classes. The same applies to abstract classes .
interface MyInter{
length: number;
}
function test<T extends MyInter>(arg: T): number{
return arg.length;
}
Example :
/* function fn(a: any): any{ return a; }*/
/* * When defining functions or classes , You can use generics if you encounter ambiguous types * * */
function fn<T>(a: T): T{
return a;
}
// You can call functions with generics directly
let result = fn(10); // Do not specify generics ,TS Types can be inferred automatically
let result2 = fn<string>('hello'); // Specifying generics
// Generics can specify multiple
function fn2<T, K>(a: T, b: K):T{
console.log(b);
return a;
}
fn2<number, string>(123, 'hello');
interface Inter{
length: number;
}
// T extends Inter For generics T When necessary Inter Implementation class ( Subclass )
function fn3<T extends Inter>(a: T): number{
return a.length;
}
class MyClass<T>{
name: T;
constructor(name: T) {
this.name = name;
}
}
const mc = new MyClass<string>(' The Monkey King ');
summary
That's all ts Some basic usage methods of , Personal feeling ts It is mainly used to limit the type , Some can be avoided from the beginning of the project bug, Compared with the background method , It is to write interface restricted types , Finally, I recommend one to you vscode Set Chinese error prompt , You need to open the setting page , Search for “typescript local”, Then set Chinese , If you feel ok , Please give me a compliment , thank you ~
边栏推荐
猜你喜欢
[面試時]——我如何講清楚TCP實現可靠傳輸的機制
C language Getting Started Guide
记一次猫舍由外到内的渗透撞库操作提取-flag
2. C language matrix multiplication
Custom RPC project - frequently asked questions and explanations (Registration Center)
Using spacedesk to realize any device in the LAN as a computer expansion screen
强化学习系列(一):基本原理和概念
编写程序,模拟现实生活中的交通信号灯。
Change vs theme and set background picture
Caching mechanism of leveldb
随机推荐
【九阳神功】2019复旦大学应用统计真题+解析
7. Relationship between array, pointer and array
【手撕代码】单例模式及生产者/消费者模式
PriorityQueue (large root heap / small root heap /topk problem)
杂谈0516
[the Nine Yang Manual] 2018 Fudan University Applied Statistics real problem + analysis
Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems
2.初识C语言(2)
撲克牌遊戲程序——人機對抗
Cookie和Session的区别
It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
【九阳神功】2018复旦大学应用统计真题+解析
2. First knowledge of C language (2)
实验四 数组
Wechat applet
Change vs theme and set background picture
canvas基础1 - 画直线(通俗易懂)
7-5 走楼梯升级版(PTA程序设计)
3. Number guessing game
使用Spacedesk实现局域网内任意设备作为电脑拓展屏