home page
Statistics
sponsor
Leaving a message.
about
more
Friendly chain
wallpaper
live broadcast
Search
one
Joe - a personal Typecho theme
32056 Reading
two
Joe open source directory program system
11825 Reading
three
Typecho custom background editor function
8240 Reading
four
Joe theme is automatically updated
7507 Reading
five
Joe Theme Custom Matching Color Tutorial
4410 Reading
web front end
CSS
React
Vue 2.0
Vue 3.0
JavaScript
TypeScript
Typecho
Applet
MacCMS
other
life
Sign in
Search
https://78.al
Accumulated writing
seventy-six
Articles
Accumulated receipt
3,721
Comments
home page
column
web front end
CSS
React
Vue 2.0
Vue 3.0
JavaScript
TypeScript
Typecho
Applet
MacCMS
other
life
page
Statistics
sponsor
Leaving a message.
about
Friendly chain
wallpaper
live broadcast
Search to
two
Article and
TypeScript
Results for
2021-04-08
TypeScript
If you want to use TypeScript quickly, you need to install TypeScript first. The installation command (global): npm i typescript - gTypeScript is progressive, and you don't need to understand the syntax of TypeScript. You can also use it. After writing code, compile *. ts files into common recognizable *. js files Command: tsc hello.ts Original data type const a: string='a ';
const b: number = 1; // NaN Infinite
const c: boolean = true; // false
const d: null = null;
const f: undefined = undefined;
const g: void = undefined;
//Union Type
let a: number | string;unknown & anylet a: any;
let b: string;
//Assign an any type to another type, allowing assignment
b = a; // √
let c: unknown;
c = 'asdasd';
//Unknown type cannot be assigned to other types
b = c; // ×
//If you want to assign c to b, you need to use the following method
//First
if(typeof c === "string") b = c
//Second, type assertion (<type>variable) is equivalent to (variable as type)
b = <string>c
B=c as stringTypeScript object type In typescript, the variable defined as object is not only an object, it represents data other than the original data type, such as function, array, etc. const obj1: object=()=>{};
const obj2: object = [];
const obj3: object = {};
When defining real objects, you can use literal or interface const obj:{
age: number;
} = {
age: 18
};
Array type defines a variable as an array type. There are two ways to const arr1: Array<number>=[1, 2, 3];
const arr2: number[] = [1, 2, 3];
// demo
function sum(...
args: number[]) {
return args.reduce((prev,
current) => prev + current, 0);
}
sum(1, 2, 3);
Tuple type const user: [string, number]=['Joe ', 18];
const [_name, _age] = user;
// demo
const obj = Object.entries({
name: 'Joe',
age: 18
});
console.log(obj); //
Obj returns the tuple type enumeration type defines an enumeration using the enum keyword. After definition, enum STATUS cannot be modified{
SUCCESS = 0,
FAIL = 1,
UNKNOW = 3
}
console.log(STATUS.
SUCCESS);
After compiling in the above way, STATUS will be compiled into a variable, which may affect the use of code. If you do not want to compile into a constant, you need to add the const keyword const enum STATUS before enum{
SUCCESS = 0,
FAIL = 1,
UNKNOW = 3
}
console.log(STATUS.
SUCCESS);
Function type 1, function declaration?
Indicates that the value is an optional function fn1 (a: number, b?: number): number{
return 1;
}
fn1(1);
2. Function expression const fn2=function (... args: number []): number{
return 1;
};
fn2();
3. No return value function fn3(): void {}
fn3();
Any type function stringify (val: any): any{
return JSON.stringify(val);
}
stringify(true);
Type assertion Type assertion has two ways. The first way is to use the as keyword let _el=document. querySelector ('. img');
let el = _el as HTMLImageElement;
el.width = 100;
The second method let _el=<HTMLImageElement>document. querySelector ('. img');
_el.width = 1;
Basic use of interface interface{
title: string;
content: string;
}
function getDetail(post: Post) {
console.log(post.title);
console.log(post.content);
}
getDetail({
title: '1',
content: 'aaa'
});
Interface optional attribute interface Post{
title: string;
content: string;
summary?: string;
}
const obj: Post = {
title: '11',
content: 'asdasd'
};
Interface Post, the dynamic property of the interface{
title: string;
content: string;
summary?: string;
[key: string]: number | string;
}
const obj: Post = {
title: '11',
content: 'asdasd',
test: 1
};
Class User{
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHi(msg: string): void {
console.log(`i am ${this.name}`);
}
}Modifier class User in class{
//Public by default
public name: string;
//Access is only allowed in the current class
private age: number;
//Only current and subclass access is allowed
protected sex: boolean;
//The attribute is read-only and cannot be modified after being defined
readonly hobby: string = 'Rap';
constructor(name: string, age: number) {
this.name = name;
this.age = age;
this.sex = true;
}
sayHi(msg: string): void {
console.log(`i am ${this.name}`);
}
}
const Tom = new User('Tom', 18);
Class and interface Eat{
eat(food: string): void;
}
interface Run {
run(): void;
}
//Person implements the Eat and Run interfaces
class Person implements Eat, Run {
eat(food: string): void {}
run() {}
}
class Animal implements Eat {
eat() {}
}Abstract class Animal{
eat(food: string): void {}
abstract run(): void;
}
class Dog extends Animal {
run() {}
}
//Dogs will have their own run method as well as their parent class's eat method
const dog = new Dog();
When defining a generic type, do not specify a specific type. When calling, pass the type.//Generate an array of numeric types
function createNumberArray(length: number, value: number): number[] {
return Array<number>(length).fill(value);
}
createNumberArray(3, 1);
//Implement the generation of an array of string type
function createStringArray(length: number, value: string): string[] {
return Array<string>(length).fill(value);
}
createStringArray(3, '');
//Use generics to implement different return types according to the passed values
function createArray<T>(length: number, value: T): T[] {
return Array<T>(length).fill(value);
}
createArray(3, 1);
createArray(3, '');
Type declaration sometimes introduces third-party modules that do not use type definitions. In this case, you need to define the type import {camelCase} from 'lodash';
declare function camelCase(input: string): string;
const str = camelCase('asdJdf');
April 8, 2021
536 Reading
6 Comments
6 likes
2021-03-09
TypeScript
Typescript is basically installed by using Typescript. Typescript files are compiled by using npm global installation Typescript npm install typescript - g,
The typescript file ends in the ts file format. It can only be run after being compiled into a js file with the help of the compiler. The compilation instruction tsc xxxx.ts is compiled in the above way, which is cumbersome. Therefore, a tsconfig.json configuration file will be created in the project root directory to set the compilation method of the ts file{
/*
*
*Included path
** * All directories, including subdirectories, * all files
*/
"include": ["./src/**/*"],
/*
*
*File directory that does not need to be compiled
*
*/
"exclude": [],
/*
*
*Compilation Options
*
*/
"compilerOptions": {
/*Target compatible version after compilation*/
"target": "ES6",
/*Modular specification*/
"module": "ES6",
/*Catalog after packaging*/
"outDir": "./dist",
/*Compile JS file or not*/
"allowJs": false,
/*Check JS code syntax specification*/
"checkJs": false,
/*Whether to remove comments*/
"removeComments": false,
/*Do not produce compiled files*/
"noEmit": false,
/*When there are errors, the compiled file will not be produced*/
"noEmitOnError": true,
/*Set the compiled file to strict mode*/
"alwaysStrict": true,
/*Implicit any type is not allowed*/
"noImplicitAny": true,
/*This of ambiguous type is not allowed*/
"noImplicitThis": true,
/*Strictly check null values*/
"strictNullChecks": true,
/*Open all and check strictly*/
"strict": true
// ...
}
}The basic syntax of Typescript defines the basic type of variable//defines the number type
const num: number = 1;
//Define string type
const str: string = 'joe';
//Define Boolean type
Const bool: boolean=true Note: null and undefined have one and only one value, so the assignment operation let _test1: null cannot be performed after declaring the variable to be null or undefined;
let _test2: undefined;
_test1 = 1; //
×
_test2 = 1; //
× If a variable is declared but no value is assigned to this value, the default value is undefined number: number//
The value of num is undefined. If no type is declared and no value is assigned, the default value is any type let num//
Num is inferred as any type null and undefined. In some cases, there will be hidden problems.
For example, let num: num=1;
num = null;
num.toFixed(2); //
In this case, the editor will not report an error, but there is a problem in the actual operation. To avoid the above situation, you need to enable the strict check mode for null and undefined by adding a line in the tsconfig.json file{
"compileOptions": {
...
//Set strict inspection
"strictNullChecks": true
}
}When defining the basic variable above, the wrapper type of the basic type: the following types are all lowercase, which means that this is the data of a basic type. If it is uppercase, it means the wrapper type of the basic type, such as let string: string='joe '//Define the string of a basic type
Str=new String ("1")//The string from × new is a wrapper type. It cannot be assigned to a simple type. When there are few attributes in the object type object, it is directly written as an inline const obj: {x: number; y: string}={
x: 1,
y: 'joe'
}If there are many attributes in the object, write them as interface type.//Use the interface keyword to define the interface
interface MyObject {
x: number;
y: string;
//Any type
[prop: string]: any;
}
//Object use interface
const obj: MyObject {
x: 1,
y: 'joe'
}Defining variables as array types The storage types of arrays in typescript must be consistent, so when you label array types, you must also label the data types stored in arrays let arr: Array<number>=[1, 2, 3]//
Short form: let arr: number []=
arr.push('11'); //
error
arr.push(22); //
Correctly define the variable as a tuple type tuple like array, but the number of initializations and corresponding positions need to be consistent with the labeled ones, and the out of bounds data must be one of the types in the labeled let arr: [string, number]=['hello ', 2];
arr.push('1'); //
correct
arr.push(1); //
correct
arr.push(true); //
Out of bounds data type Error defining enumeration type enum HTTP_CODE{
SUCCESS = 200,
ERROR = 201,
URL
}
HTTP_CODE.URL,
Once defined, it cannot be modified. To define any type, sometimes it is not sure what type the value is, it can be marked as any type const a: any=1;
Note for any type: a variable states that any type value can be assigned to any type by default when it is not assigned and not marked. Any type has any attribute and method marked as any type, which means that the type check for the value is abandoned, and the editor's prompt to define the unknown type is an unknown type of any type in the security version is also abandoned.
For example, because any can be assigned to any type, the following demo will report an error and cannot check let a: any='1 ';
let b: number = 1;
b.toFixed(2);
b = a;
//Can't detect
b.toFixed(2);
Change to unknown type let a: unknown='1 ';
let b: number = 1;
b.toFixed(2);
B=a;//An error is reported.
Unknown type cannot be assigned to other types
b.toFixed(2);
Note for using unknown: unknown type can only be assigned to unknown, and any unknown type does not have any attribute and method definition. Function without return value type means the type without data. It is usually used to mark the return value type of function without return value. The default marking type of function is void function fn(): void{
console.log("joe")
}Define a function as the never type. When a function can never execute return, it returns never. Unlike void, void executes return but has no value. Never will not execute return, such as throwing an error that causes the function to stop executing functionfn(): never{
throw new Error('error');
}Define the return value of the function type The function type can be marked with the return value type and parameter type, such as function fn (x: number): number{
return x;
}Use of interface Basic use of interface Point{
x: number;
y: number;
}
const point: Point = {
x: 1,
y: 1
}Interface Optional Attribute The interface can define optional attributes by using the?
Make a dimension?
Indicates that the value is an optional interface point{
x: number;
y: number;
z?: string;
}Interface Attribute Read only The interface can define read-only attributes and use readonly to label them. After labeling, it means that the attribute value cannot be modified{
readonly x: number;
readonly y: number;
}
const point: Point = {
x: 1,
y: 2
}Interface Any type interface point{
x: number;
y: string;
[key: string]: any;
}
const point = {
x: 1,
y: 'hello',
z: 1
}Describe the function through the interface//Define it through the interface
interface Func {
(e: Event): void;
}
const fn: Func = (e: Event) => {};
//Direct definition
function fn(el: HTMLElement, callback: (e: Event) => number) {}
const div = document.querySelector('div');
fn(div, function () {
return 1;
});
Interface name duplication merging If two interfaces with duplicate names are written, these two interfaces will be merged interface points{
x: number;
y: number;
}
interface Point {
z: string;
}
const point: Point = {
x: 1,
y: 1,
z: '11'
};
Joint type If a variable can use multiple types, | can be used for split representation or function fn (el: HTMLElement, attr: string, value: string | number) {}
const div = document.querySelector('div');
fn(div, 'a', 1);
Cross type interface O1{
x: number;
}
interface O2 {
y: number;
}
const o: O1 & O2 = Object.assign({}, { x: 1 }, { y: 2 });
Note: An error will be reported above, saying that there is no assign method on the object. At this time, you only need to add the lib library of es in tsconfig.json to solve the problem{
"compilerOptions": {
...
"lib": ["ES6"]
}
}In actual use, literal types are often allowed to accept only a few fixed values. When other values are not allowed to be accepted, the literal type function fn (direction: 'left' | 'right') {} can be used
fn('left');
Type alias continues to the literal type above. If there are too many literal values, type alias should be used.//Normal use
type direction = 'left' | 'right';
function fn(direction: direction) {}
fn('left');
//Defining Functions
Type fn=(a: number)=>number type derivation In actual development, these types have to be written every time you define variables, parameters, etc. It is very troublesome, so there is type derivation, which automatically deduces the type const a='111 'according to the context code.//At this time,
The type of a will be automatically recognized as a string type type assertion. The default type derivation range may be wide. If you need to narrow the range, you need to use the type assertion const img=<HTMLImageElement>document. querySelector ('img ');
if (img) {
img.src = '';
}Functions can be labeled in the following ways/* The first way*/
function fn(a: number): number {
return 1;
}
fn(1);
/*Second*/
const fn2: (a: number) => number = function (a) {
return 1;
};
fn2(2);
/*Third*/
type CallBack = (num: number) => number;
const fn3: CallBack = function (num) {
return 1;
};
fn3(1);
/*Fourth*/
interface Fn {
(num: number): number;
}
let fn4: Fn = function (num) {
return 1;
};
fn4(2);
Optional parameter function fn (el: HTMLElement, attr: string, val?: number) {}
fn(document.querySelector('div'), 'width', 1);
Parameter default value function fn (attr: 'left' | 'right'='left') {}
fn('left');
Remaining parameters interface Rest{
[key: string]: any;
}
function fn(target: Array<number>, ...
rest: Array<Rest>) {}
fn([1]);
This annotation method in function interface T{
x: number;
fn:(x: number) => void
}
const obj: T = {
x: 1,
fn(this: T, x: number){
this.x
}
}For example, there is an example of function overload. In the following functions, the first parameter is a dom element, the second parameter is display or efficiency, and the third parameter is a number or string function setStyle (el: HTMLElement, attr:'display '|'opacity', val:'block '|'none' | number){
...
}The above parameters can be written like this, but if you want to pass in the display, the third value must be block or none, so you can use function overloading to implement function fn (el: HTMLElement,
attr: 'display', val: 'block' | 'none'): void
function fn(el: HTMLElement,
attr: 'opacity', val: number): void
Function fn (el: HTMLElement, attr: string, val: any) {} Basic use of class person{
/*Properties defined on the instance*/
Name='Du Heng';
/*Properties defined on the class*/
static age = 18;
/*Method defined on instance*/
static say() {
console.log(1);
}
}
const duHeng = new Person()
console.log(duHeng)
The constructor class Dog of the console. log (Person) class{
name: string;
age: number;
/*This constructor function will be called when an object is instantiated*/
constructor(name: string, age: number) {
/*This points to the instance generated by the current instance*/
console.log(this);
this.name = name;
this.age = age;
}
}
Const WangCai=new Dog ('WangCai ', 1);
Const XiaoBai=new Dog ('Xiaobai ', 2);
console.log(WangCai);
console.log(XiaoBai);
In typescript, define the static attribute of a class, use the public keyword, and after use, it will be automatically set as a parameter and assigned a value. The above writing method is equivalent to the following class dog{
constructor(public name: string, public age: number) {
// ...
}
}Attribute modifier class User in class{
constructor(
//Public attribute, public by default
public host: number
//Can be accessed, but cannot be modified
readonly id: number,
//It can only be accessed internally and subclasses, but cannot be modified externally
protected username: string,
//External and subclass cannot be accessed, only the current can access
private password: string
) {
}
}
const user = new User(1, 'Joe', '123')
User.id;//Accessible
User.id=1;//× cannot be modified
User.username;//× unreadable
User.password;//× unreadable After the above password is set to a private property, the external cannot be accessed and modified. However, if you want to read and modify externally, you need to use the register class User{
constructor(private _password: string) {}
//Used to set private property password
set password(newPassword: string) {
this._password = newPassword;
}
//Used to obtain private property password
get password(): string {
return '****';
}
}
const user = new User('1');
user.password = '111';
The static member type FileList in the user.password class='gif '|'png' |'jpg '
class User {
//The static defined attribute only exists in the class, not in the instance
static readonly FILE_LIST: Array<FileList> = ['gif', 'png']
}Abstract class/*
*
*Declared as an abstract class, this class cannot be new
*An abstract class is a class that is specifically used to be inherited
*
*/
abstract class Component {
constructor(public props: any) {}
/*If the method is declared abstract, the class must also be declared abstract*/
abstract render(): void;
}
class SonComponent extends Component {
render() {}
}
new SonComponent(1);
Specification class, implementation class inherits multiple interfaces interface Info{
getInfo(): string;
}
class A implements Info {
getInfo() {
return '';
}
}In many cases, the specific type of the annotation cannot be determined, so the generic interface interface needs to be used{
length: number;
}
function fn<T extends Inter>(obj: T) {
return obj.length;
}
fn('sdasd');
const obj1 = {
x: 1,
y: 2
}
const obj2 = {
a: 1,
b: 2
}
function fn<T>(obj: T, k: keyof T) {
return obj[k]
}
fn<typeof obj1>(obj1, 'x')interface Res<T> {
code: number;
message?: string;
data: T;
}
interface data {
name: string;
age: number;
}
async function getData<U>(url: string) {
let response = await fetch(url);
let data: Promise<Res<U>> = await response.json();
return data;
}
(async function () {
const res = await getData<data>('/user');
})();
March 9, 2021
625 Reading
2 Comments
6 likes