声明文件
what is type script
add type system on top layer of js;
for primitive Data
for compound Data
use interface to describe tyep
1
2
3
4
5
6
7
8
9
|
interface User {
name: string;
id: number;
}
// option properties
interface SquareConfig {
color?: string;
width?: number;
}
|
use interface as a function type
1
2
3
4
5
6
7
8
9
|
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function (source: string, subString: string) {
let result = source.search(subString);
return result > -1;
};
|
use interfae as class type
1
2
3
4
5
6
7
8
9
10
11
12
|
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {}
}
|
union type
1
2
3
|
let a: true | "1";
a = true ;
a = "1"
|
generic
in a nutshell, generic enable types to be parameters when defining classes, methods, ionterfaces
- generic interface type
1
2
3
4
5
|
interface Dog<T>{
name: T
}
var d: Dog<string> = {name:"123"}
|
- generic function type
interface EatFunc{
(arg:T):T;
}
function Eattt(arg:T):T {
return arg
}
let me:EatFunc = Eattt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
3. generic class type
```ts
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};
|
.d.ts
declare file;
用于调用非Typescript 库