typescript使用
函数参数带类型
interface Shape {
name: string;
width: number;
height: number;
color?: string;
}
function area(shape : Shape) {
var area = shape.width * shape.height;
return "I'm " + shape.name + " with area " + area + " cm squared";
}
console.log( area( {name: "rectangle", width: 30, height: 15} ) );
console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );
类 class
class Shape {
area: number;
color: string;
constructor ( name: string, width: number, height: number ) {
this.area = width * height;
this.color = "pink";
};
shoutout() {
return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
}
}
var square = new Shape("square", 30, 30);
console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
继承
class Shape3D extends Shape {
volume: number;
constructor ( public name: string, width: number, height: number, length: number ) {
super( name, width, height );
this.volume = length * this.area;
};
shoutout() {
return "I'm " + this.name + " with a volume of " + this.volume + " cm cube.";
}
superShout() {
return super.shoutout();
}
}
var cube = new Shape3D("cube", 30, 30, 30);
console.log( cube.shoutout() );
console.log( cube.superShout() );
基础类型
boolean/number/string/数组/元组 Tuple/枚举/any/void/null/undefined
let isDone: boolean = false;
let decLiteral: number = 6;
let name: string = "bob";
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
let x: [string, number];
enum Color {Red, Green, Blue}; 默认情况下,从0开始为元素编号
let c: Color = Color.Green;
let colorName: string = Color[2];由枚举的值得到它的名字
类型断言:
用<>表示:let strLength: number = (<string>someValue).length;
用as:let strLength: number = (someValue as string).length;
接口
interface LabelledValue {
label: string;
}
可选属性
interface SquareConfig {
color?: string;
width?: number;
}
只读属性
interface Point {
readonly x: number;
readonly y: number;
}
额外的类型检查
对象字面量存在任何“目标类型”不包含的属性时,你会得到一个错误。
let mySquare = createSquare({ colour: "red", width: 100 });
函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
可索引类型
能够“通过索引得到”的类型,可索引类型具有一个索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。
interface StringArray {
[index: number]: string;
}
myArray = ["Bob", "Fred"];
实现接口
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
}
扩展接口
一个接口可以继承多个接口
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
混合类型
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
接口继承类
继承类的成员但不包括其实现
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
类
class Animal {
name:string;
private xx: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
当成员被标记成private时,它就不能在声明它的类的外部访问;
protected能在子类中访问
readonly关键字将属性设置为只读的。
存取器
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
抽象类
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('roaming the earch...');
}
}
因为类可以创建出类型,所以你能够在可以使用接口的地方使用类。
class Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
函数类型
function add(x: number, y: number): number {
return x + y;
}
let myAdd = function(x: number, y: number): number { return x+y; };
let myAdd: (x:number, y:number)=>number =
function(x: number, y: number): number { return x+y; };
泛型
function identity(arg: number): number {
return arg;
}
->
function identity(arg: any): any {
return arg;
}
-> 泛型,捕获用户输入的类型,然后使用这个类型。
function identity<T>(arg: T): T {
return arg;
}
let output = identity("myString");
let myIdentity: <T>(arg: T) => T = identity;
泛型类
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
泛型约束
创建一个包含.length属性的接口,使用这个接口和extends关键字还实现约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}
在泛型约束中使用类型参数
function find<T, U extends Findable<T>>(n: T, s: U) {
// ...
}
find (giraffe, myAnimals);
泛型中使用类类型
function create<T>(c: {new(): T; }): T {
return new c();
}
高级类型
联合类型:用|分割
要么为A,要么为B这样。
交叉类型
将多个类型合并为一个类型
既可以为A,又可以为B这样
Person & Serializable & Loggable
类型保护:
1. 使用类型断言
if ((<Fish>pet).swim) {
(<Fish>pet).swim();
}
else {
(<Bird>pet).fly();
}
2. typeof类型保护
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
3. instanceof 类型保护
if (padder instanceof SpaceRepeatingPadder) {
}
4. 去除null类型
return x || 'default'
或者通过 identifier!
name!.charAt(0)
5. 类型别名
给一个类型起新的名字
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
type Container<T> = { value: T };
type Tree<T> = {
value: T;
left: Tree<T>;
right: Tree<T>;
}
type LinkedList<T> = T & { next: LinkedList<T> };
6. 接口和类型别名区别
接口创建新的名字,类型别名不会;
type Alias = { num: number }
interface Interface {
num: number;
}
类型别名不会被extends和implements
7. 字符串字面量类型
type Easing = "ease-in" | "ease-out"
8. 可辨识联合
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Square | Rectangle;
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
}
}
9. 索引类型
索引类型查询和索引访问操作符
keyof T 返回 T的属性名联合。
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
return names.map(n => o[n]);
}
10.
iterator
for...of
可以遍历可迭代对象
for...of和for...in
可以遍历列表,for...in迭代的是对象的键的列表,for...of迭代的是对象的值的列表
模块
模块在自身作用域中执行,而不是全局作用域。
模块内的变量、函数只能在内部访问,模块外部不可见。可以通过export导出,import导入。
export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };
export {ZipCodeValidator as RegExpBasedZipCodeValidator} from "./ZipCodeValidator";
export * from "module"
import { ZipCodeValidator } from "./ZipCodeValidator";
import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
import * as validator from "./ZipCodeValidator";
import "./my-module.js";
规范
1. 基本类型用number、string、boolean
2. 没有返回值用void
function fn(x:()=> void){x()}
3.