TypeScript 接口(三)

TypeScript的核心原则之一是对值所具有的结构进行类型检查。

接口初始:

interface objProperty {
    name: string
}

function printName(nameObject: objProperty) {
    console.log(nameObject.name);
}

let obj = { age: 11, name: 'Name is Sunny' };

printName(obj);

注意,类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。

可选属性:

可选属性名字定义的后面加一个?符号。

可选属性的好处

  • 可以对可能存在的属性进行预定义,
  • 可以捕获引用了不存在的属性时的错误。 
interface SquareConfig {
  color?: string;
  width?: number;
}

只读属性:

只读属性只能在对象刚刚创建的时候修改其值。

interface Point {
    readonly x: number;
    readonly y: number;
}
let p1: Point = { x: 10, y: 20 };// 赋值后, xy再也不能被改变了。
p1.x = 5; // error!

TypeScript具有ReadonlyArray<T>类型,它与Array<T>相似,只是把所有可变方法去掉了,因此可以确保数组创建后再也不能被修改:

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!

上面代码的最后一行,可以看到就算把整个ReadonlyArray赋值到一个普通数组也是不可以的。 但是你可以用类型断言重写:

a = ro as number[];

readonly vs const

最简单判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用readonly

实现接口:implements 

接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date);
}

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

继承接口:extends 

和类一样,接口也可以相互继承。 这让我们能够从一个接口里复制成员到另一个接口里,可以更灵活地将接口分割到可重用的模块里。

一个接口可以继承多个接口,创建出多个接口的合成接口。

interface Shape {
    color: string;
}

interface PenStroke { penWidth: number; } interface Square extends Shape { sideLength: number; }

interface Square extends Shape, PenStroke {
  name: string;
}
let square
= <Square>{}; square.color = "blue"; square.sideLength = 10;

 

 

posted @ 2018-09-10 09:50  猪快跑  阅读(429)  评论(0编辑  收藏  举报