拱 溪石的博客NOTES & CODE
首页/js/typescript
js · 2023-07-07 发布

typescript

TypeScript:从基础类型到泛型

Typescript 基础

js是个弱类型语言,动态语言即,变量的类型是不确定的。弱类型灵活,但是强类型更有利,可以降低系统的复杂度,在编译时检查类型错误。

ts属于 JavaScript 的超集,可以编译为 JavaScript 执行。 它的最大特点就是支持强类型和ES6 class

文档:https://www.tslang.cn/docs/handbook/basic-types.html

起步

npm install -g typescript

tsc -w watch文件

tsc xx.ts 编译ts文件

tsc –init 初始化配置 tsconfig.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
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
//定义基础类型
let a: boolean = false
let num1:number =1
let num2:number = 0x12
let name1: string = "zhangsan"
//数组定义方式
let list:any[]=[1,2,3]
let list2:Array<number>=[4,5,6]
list2.push(34)

//元组类型允许表示一个已知元素数量和类型的数组
let xtuple: [string, number];
xtuple=["dw",33]

// 枚举类型,实际转化为了
//
enum Color{
Red,
Green,
Blue
}

let colorValue: Color = Color.Green;
let colorName:String = Color[2]

let typeAny:any = 1;

//object表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。
let typeObject:object = {};

// void类型 严格模式只有undefine 非严格模式undefine、null
let voidVal: void ;

voidVal=null
function fun():void {
}

let fun1=():void=> void


//never类型表示的是那些永不存在的值的类型。 例如, never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型
function error(message: string): never {
throw new Error(message);
}

let error1=():never=>{
throw new Error('ddd');
}

// 类型断言
//“尖括号”语
let someValue: any = "this is a string";

let strLength1: number = (<string>someValue).length;

// as语法
let strLength2: number = (someValue as string).length;


元组的实际形式

TypeScript 元组示例

默认情况下null和undefined是所有类型的子类型。 就是说你可以把 null和undefined赋值给number类型的变量。

image-20230711150447259

函数、接口、对象

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
interface SquareConfig {
color?: string;
width?: number;
}

function createSquare(config:SquareConfig):{color:string;area:number} {
let newSquare = {
color:"white",
area:100
}
if(config.color) {
newSquare.color=config.color
}
if(config.width) {
newSquare.area = config.width*config.width
}
return newSquare
}

let mySquare = createSquare({color: "black"});
console.log(mySquare)


interface Point {
readonly x:number; // 数组的使用ReadonlyArray<number>
y:number
}
let a:Point = {
x:122,
y:33
}
a.x=2 ///报错


(a as {}).x=3 // 可以断言绕过去 乱用
// 最简单判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用readonly。




接口 : 接口能够描述JavaScript中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外,接口也可以描述函数类型。

可索引的类型:

可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 number 来索引时,JavaScript 会将它转换成 string 然后再去索引对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}

interface NotOkay {
[x: string]: Dog;
[x: number]: Animal; // Error
}

interface Okay {
[x: string]: Animal;
[x: number]: Dog; // OK
}

类实现接口

1
2
3
4
5
6
7
8
9
10
11
12
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}

class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}

接口继承接口

1
2
3
4
5
6
7
8
9
interface Shape {
color: string;
}

interface Square extends Shape {
sideLength: number;
}
let square = <Square>{};

混合类型:一个对象可以同时做为函数和对象使用,并带有额外的属性。

类

由于类名作为类型使用,实际上代表一个对象,因此可以把类看作为对象类型起名。事实上,TypeScript 有三种方法可以为对象类型起名:type、interface 和 class。

class表示的实例类型 ,如果要获取自身类型,typeof 语法,或者类本身是一种构造函数,所以可以用构造函数写法

1
2
3
4
5
6
7
function createPoint(
PointClass: new (x:number, y:number) => Point,
x: number,
y: number
):Point {
return new PointClass(x, y);
}

泛型

有些时候,函数返回值的类型与参数类型是相关的。 泛型的特点就是带有“类型参数”(type parameter)

函数调用的时候一般要具体指定类型,也可以让ts推断。复杂场景还是需要指定

1
2
3
function comb<T>(arr1:T[], arr2:T[]):T[] {
return arr1.concat(arr2);
}
  1. 函数泛型(function关键字定义的泛型函数,类型参数放在尖括号中,写在函数名后面。)

    1
    2
    3
    function id<T>(arg:T):T {
    return arg;
    }

    变量定义的函数

    1
    let myId:<T>(arg:T) => T = id;
  2. 接口的泛型写法

    1
    2
    3
    4
    5
    interface Box<Type> {
    contents: Type;
    }

    let box:Box<string>;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    interface Comparator<T> {
    compareTo(value:T): number;
    }

    class Rectangle implements Comparator<Rectangle> {

    compareTo(value:Rectangle): number {
    // ...
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 接口定义方法里面
    nterface Fn {
    <Type>(arg:Type): Type;
    }

    function id<Type>(arg:Type): Type {
    return arg;
    }

    let myId:Fn = id;
typescript
https://blog.dayday.cyou/2023/07/07/typescript/
作者
溪石
发布于
2023年7月7日
许可协议