class1.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
abstract class Animal {
eat(){
console.log('eat');
}
abstract sleep(): void;
}

class Dog1 extends Animal{
constructor(name: string) {
super();
this.name = name;
}
name: string
run(){}
sleep(){
console.log('dog sleep');
}
}
let dog1 = new Dog1('wangwang');
dog1.eat();

class Cat extends Animal{
sleep(){
console.log('Cat sleep');
}
}
let cat = new Cat();

let animals: Animal[] = [dog1, cat]
animals.forEach(i=>{
i.sleep();
})

class WorkFlow {
step1(){
return this;
}
step2(){
return this;
}
}
new WorkFlow().step1().step2();

class Myflow extends WorkFlow{
next(){
return this;
}
}
new Myflow().next().step1().step2();
阅读全文 »

class.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Dog{
constructor(name: string) {
this.name = name;
}
public name: string = 'dog';
run(){}
private pri(){}
protected pro(){}
readonly legs: number = 4
static food: string = 'bones'
}
console.log(Dog.prototype);
let dog = new Dog('wangwang');
console.log(dog)
// dog.pri()
// dog.pro()
console.log(Dog.food)

class Husky extends Dog {
constructor(name: string, public color: string) {
super(name);
this.color = color;
// this.pri()
this.pro();
}
// color: string;
}
console.log(Husky.food)
阅读全文 »

function.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 函数定义
function add1(x:number, y:number){
return x + y;
}

let add2: (x:number, y:number) => number

type add3 = (x:number, y:number) => number

interface add4{
(x:number,y:number): number;
}

// add1(1,2,3)

function add5(x:number,y?:number){
return y?x+y:x;
}
add5(1)

function add6(x:number,y=0,z:number,q=1){
return x + y + z + q;
}
console.log(add6(1,undefined, 3));

function add7(x:number,...rest:number[]){
return x + rest.reduce((pre, cur)=> pre +cur) ;
}

console.log(add7(1,2,3,4,5))

function add8(...rest: number[]): number;
function add8(...rest: string[]): string;
function add8(...rest: any[]): any{
let first = rest[0];
if(typeof first === 'string'){
return rest.join('')
}
if(typeof first === 'number'){
return rest.reduce((pre, cur)=> pre + cur);
}
}
console.log(add8(1,2,3));
console.log(add8('a','b','c'));
阅读全文 »

interface1.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// let add: (x:number,y:number) => number

// interface Add{
// (x:number, y:number): number
// }

type Adds = (x: number, y:number) => number

let adds: Adds = (a, b) => a + b

interface Lib{
():void;
version: string;
doSomething():void
}

function getLib(){
let lib: Lib = (() => {}) as Lib
lib.version = '1.0';
lib.doSomething = () => {}
return lib;
}

let lib1 = getLib();
lib1();
lib1.doSomething();

let lib2 = getLib();

阅读全文 »

interface.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
interface List {
readonly id: number,
name:string,
// [x: string]: any;
age?: number
}
interface Result {
data:List[]
}
function render(result: Result) {
result.data.forEach((value) => {
console.log(value.id, value.name);
if (value.age) {
console.log(value.age);
}
// value.id++
});
}
const result = {
'data': [
{ 'id': 1, 'name': 'A', 'sex': 'male' },
{ 'id': 2, 'name': 'B', 'age': 10 }
]
};
render(result);

interface StringArray{
[index: number]: string
}
let chars: StringArray = ['A', 'B']

interface Names{
[x: string]: any;
// y: number;
[z: number]: number
}

// render(<Result>{
// 'data': [
// { 'id': 1, 'name': 'A', 'sex': 'male' },
// { 'id': 2, 'name': 'B' }
// ]
// } as Result);
// render(<Result>{
// 'data': [
// { 'id': 1, 'name': 'A', 'sex': 'male' },
// { 'id': 2, 'name': 'B' }
// ]
// });
阅读全文 »

  • 在src文件夹中新建enum.ts文件,在index.ts中引入该文件

index.ts

1
2
3
4
5
import './datatype';
import './enum'; // 新增这句话
let hello : String = 'Hello TypeScript';
document.querySelectorAll('.app')[0].innerHTML = 'hello';

enum.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 06-枚举类型

// 数字枚举
enum Role {
Reporter = 1,
Developer,
Maintainer,
Owner,
Guest
}
console.log(Role.Reporter)
console.log(Role)

// 字符串枚举
enum Message {
Success = '恭喜你,成功了',
Fail = '抱歉,失败了'
}
console.log(Message)

// 异构枚举,容易混淆,不建议使用
enum Answer {
N,
Y = 'Yes'
}

// 枚举成员
// Role.Reporter = 2
enum Char {
// const
a,
b = Char.a,
c= 1 + 3,
d = Math.random(),
e = '123'.length,
f = 4
}
console.log(Char)

// 常量枚举
const enum Month {
Jan,
Feb,
Mar
}
let month = [Month.Jan, Month.Feb, Month.Mar]
console.log(month)

// 枚举类型
enum E { a, b}
enum F { a = 0, b = 1}
enum G { a = 'apple', b = 'banana'}

let e: E = 3
let f: F = 3
// e === f

let e1: E.a = 1
let e2: E.b
// e1 === e2
let e3: E.a = 1
e1 === e3

let g1: G = G.b
let g2: G.a = G.a
阅读全文 »

ES6 的数据类型 与 TypeScript 的数据类型

ES6 的数据类型 TypeScript 的数据类型
Boolean Boolean
Number Number
String String
Array Array
Function Function
Object Object
Symbol Symbol
undefined undefined
null null
void
any
never
元组
枚举
高级类型

###类型注解

作用:相当于强类型语言中的类型声明
语法:(变量/函数):type

  • 在src文件夹中新建datatype.ts文件,在index.ts中引入该文件

index.ts

1
2
3
4
import './datatype'; // 新增这句话

let hello : String = 'Hello TypeScript';
document.querySelectorAll('.app')[0].innerHTML = 'hello';

datatype.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 原始类型
let bool: boolean = true;
let num: number | undefined | null = 123;
let str: string = 'abc';
// str = 123; // TS2322: Type 'number' is not assignable to type 'string'.

// 数组
let arr1: number[] = [1, 2, 3];
let arr2: Array<number | string> = [1, 2, 3, '666'];

// 元组
let tuple: [number, string] = [0, '1'];

// 函数
let add = (x: number, y:number) => x + y;
let compute: (x: number, y: number) => number;
compute = (a, b) => a + b;

// 对象
let obj: {x: number, y: number} = {x: 1, y: 2};
obj.x = 3;

// symbol
let s1: symbol = Symbol();
let s2 = Symbol();
console.log(s1 === s2);

// undefined, null
let un: undefined = undefined;
let nu: null = null;
num = undefined; // TS2322: Type 'undefined' is not assignable to type 'number'.
num = null; // TS2322: Type 'null' is not assignable to type 'number'.

// void
let noReturn = () => {};

// any
let x;
x = 1;
x = [];
x = () => {}

// never
let error = () => {
throw new Error('error');
}
let endless = () => {
while(true) {}
}
阅读全文 »

  1. 初始化package.json
    npm init -y

  2. 全局安装TypeScript
    npm i typescript -g

  3. 初始化TypeScript
    tsc --init

  4. 新建一个src目录并创建一个index.ts文件并写入以下内容
    let hello : string = 'Hello TypeScript'

  5. 编译该文件
    tsc ./src/index.ts

  6. 执行后生成一个index.js文件并生成以下内容
    var hello = 'Hello TypeScript';

  7. 安装打包工具
    npm i webpack webpack-cli webpack-dev-server -D

  8. 创建build目录,用来存放所有的配置文件,并创建4个配置文件
    webpack.config.js
    webpack.base.config.js
    webpack.dev.config.js
    webpack.pro.config.js

  9. 其中webpack.base.config.js内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    const HtmlWebpackPlugin = require('html-webpack-plugin');

    module.exports = {
    entry: './src/index.ts', // 指定入口文件
    output: {
    filename: 'app.js' // 输出的文件名为app.js
    },
    resolve: {
    extensions: ['.js', '.ts', 'tsx'] // 输出的目录是默认的,输出的扩展名,js,ts,tsx
    },
    module: {
    rules: [
    {
    test: /\.tsx?$/i, // 正则以ts或者tsx为结尾的文件
    use: [{
    loader: 'ts-loader', // 使用ts-loader, npm i ts-loader typescript -D
    }],
    exclude: /node_modules/ // 排除node_modules文件
    }
    ]
    },
    plugins: [
    new HtmlWebpackPlugin({ // 插件,通过一个模板帮助我们生成网站的一个首页并把输出文件自动嵌入文件中
    template: "./src/tpl/index.html" // npm i html-webpack-plugin -D
    })
    ]
    }
  10. 需要安装以下依赖

    1
    2
    npm i ts-loader typescript -D
    npm i html-webpack-plugin -D
  11. 在src目录下新建/tpl/index.html文件并写入以下内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport"
    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TypeScript in Action</title>
    </head>
    <body>
    <div class="app"></div>
    </body>
    </html>
  12. 其中webpack.dev.config.js内容

    1
    2
    3
    module.exports = {
    devtool: 'cheap-module-eval-source-map'
    }
  13. 其中webpack.pro.config.js内容

    1
    2
    3
    4
    5
    6
    7
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');

    module.exports = {
    plugins: [
    new CleanWebpackPlugin // 每次成功构建后清空目录
    ]
    }
  14. 需要安装以下依赖

    1
    npm i clean-webpack-plugin -D
  15. 其中webpack.config.js内容

    1
    2
    3
    4
    5
    6
    7
    8
    const { merge } = require('webpack-merge');
    const baseConfig = require('./webpack.base.config');
    const devConfig = require('./webpack.dev.config');
    const proConfig = require('./webpack.pro.config');

    let config = process.NODE_EVN === 'development' ? devConfig : proConfig;

    module.exports = merge(baseConfig, config); // 使这些文件合并 npm i webpack-merge -D
  16. 需要安装以下依赖

    1
    npm i webpack-merge -D
  17. 修改npm的脚本,打开package.json文件并修改以下内容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    {
    "name": "ts-in-action",
    "version": "1.0.0",
    "description": "",
    "main": "./src/index.ts", // 修改这个
    "scripts": {
    "start": "webpack serve --mode=development --config ./build/webpack.config.js", // 增加这个
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^4.5.1",
    "ts-loader": "^8.0.14",
    "typescript": "^4.1.3",
    "webpack": "^5.19.0",
    "webpack-cli": "^4.4.0",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.7.3"
    }
    }
  18. 运行npm start

  19. 修改index.ts文件并输入以下内容

    1
    2
    let hello : String = 'Hello TypeScript'
    document.querySelectorAll('.app')[0].innerHTML = 'hello';
  20. 可以看到页面输入内容改为了hello

  21. 编写package.json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    {
    "name": "ts-in-action",
    "version": "1.0.0",
    "description": "",
    "main": "./src/index.ts",
    "scripts": {
    "start": "webpack serve --mode=development --config ./build/webpack.config.js",
    "build": "webpack --mode=production --config ./build/webpack.config.js", // 新增这个
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^4.5.1",
    "ts-loader": "^8.0.14",
    "typescript": "^4.1.3",
    "webpack": "^5.19.0",
    "webpack-cli": "^4.4.0",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.7.3"
    }
    }
  22. 运行npm run build,可以看到目录下生成了dist文件夹,这就打包好了

阅读全文 »

本站主页:
https://www.guoyu.ren/

  • 添加next主题【已使用】

    1
    git clone https://github.com/theme-next/hexo-theme-next themes/next
  • 设置顶部页面加载进度条【已使用】

    1
    git clone https://github.com/theme-next/theme-next-pace source/lib/pace
  • Canvas-nest 背景【已使用】

    1
    git clone https://github.com/theme-next/theme-next-canvas-nest source/lib/canvas-nest
    1
    2
    3
    4
    5
    6
    7
    8
    9
    # Canvas-nest
    # Dependencies: https://github.com/theme-next/theme-next-canvas-nest
    canvas_nest:
    enable: true
    onmobile: false # 是否在手机上显示
    color: "0,0,255" # RGB颜色值, 用 ',' 分隔
    opacity: 0.5 # 线条透明度: 0~1
    zIndex: -1 # 背景的 z-index 属性值
    count: 99 # 线条数量
  • Canvas-ribbon 背景【未使用】

    1
    git clone https://github.com/theme-next/theme-next-canvas-ribbon source/lib/canvas-ribbon
阅读全文 »