typescript用法

typescript的使用与需要注意的问题

基本用法

基础数据类型(数值、字符串等): let isDone: boolean = false
引用数据类型(数组、对象等): let list: number[] = [1, 2, 3]
枚举:

1
2
enum Color {Red, Green, Blue}
let c: Color = Color.Green

any(不确定类型): let notSure: any = 4
void:一般函数没有返回值时使用

1
2
3
function warnUser(): void {
console.log("This is my warning message");
}

使用接口(interface)

用法,比如想让某个对象有某个类型的属性,名字也确定:

1
2
3
4
5
6
7
8
interface LabelledValue {
label: string;//必须有
number?: number;//可选
readonly y: number;//只读,不能改
}
//含义:定义为LabelledValue类型的对象必须有一个string类型的label属性
//number属性可选,可以没有,有的话必须是number类型
//顺序不重要,存在就可以通过检查

看一个完整点的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//两个属性均为可选
interface SquareConfig {
color?: string;
width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = {color: "white", area: 100};
if (config.clor) {
// Error: Property 'clor' does not exist on type 'SquareConfig'
//拼写错误会报错,因为没有clor属性
newSquare.color = config.clor;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}

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

这就是基本的使用,可是这样会产生一个问题——你无法在参数中添加其他属性,只能是color和width,类型还不能错,如何解决这个问题呢?
可以这样定义:

1
2
3
4
5
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}

表示的是SquareConfig可以有任意数量的属性,并且只要它们不是color和width,那么就无所谓它们的类型是什么。
看到这,其实函数也是可以用接口定义的:

1
2
3
4
5
6
7
8
9
10
11
//接口定义
interface SearchFunc {
(source: string, subString: string): boolean;
}
:前面是参数类型,后面是返回值类型
//函数的使用
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}

注意,这里参数名可以改的哦,比如这样写:

1
2
3
4
5
let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
let result = src.search(sub);
return result > -1;
}

可以大概理解成实参与形参,属性类型匹配即可。

接口继承

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

interface Square extends Shape {
sideLength: number;
}//继承了color属性

也可以这样

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

interface PenStroke {
penWidth: number;
}

interface Square extends Shape, PenStroke {
sideLength: number;
}
上一篇

isNaN问题