TypeScript 学习笔记2 接口

2019-08-09  本文已影响0人  躺希腊额阿毛

接口:行为抽象

// 接口定义
interface Iprinter {
    Printing(msg:string): string;
}
// 1.实现接口,要实现里面的内容
// 2.定义接口的时候,只定义声明即可,不包含具体内容
class colorprinter implements Iprinter {
    Printing(msg:string): string {
        return "打印" + msg + "成功!";
    }
}
let p1 = new colorprinter();
let val = p1.Printing("简历");
console.log(val);

// 对函数的约束
interface Imyfunction {
    (a:string,b:number):boolean;
}
let fun1:Imyfunction;
fun1 = function(a:string,b:number):boolean {
    return false;
}

// 对数组
interface Istuarr {
    [index:number]:string;
}
let arr1:Istuarr;
arr1 = ["aaa", "bb"];
console.log(arr[0]);

// json
interface IData {
    name: string,
    readonly age: number, // 只读属性
    email?: string // 可选属性
}
function showdata(n:IData) {
    // n.age = 18;
    console.log(JSON.stringify(n));
}
showdata({name: "zhangsan", age: 10});

接口 vs. 类型别名

其一,接口创建了一个新的名字,可以在其它任何地方使用。 类型别名并不创建新名字—比如,错误信息就不会使用别名。 在下面的示例代码里,在编译器中将鼠标悬停在interfaced上,显示它返回的是Interface,但悬停在aliased上时,显示的却是对象字面量类型。
另一个重要区别是类型别名不能被extendsimplements(自己也不能extendsimplements其它类型)。 因为软件中的对象应该对于扩展是开放的,但是对于修改是封闭的,你应该尽量去使用接口代替类型别名。

另一方面,如果你无法通过接口来描述一个类型并且需要使用联合类型或元组类型,这时通常会使用类型别名。

type Alias = { num: number }
interface Interface {
    num: number;
}
declare function aliased(arg: Alias): Alias;
declare function interfaced(arg: Interface): Interface;

Typescript从0到1-学习视频教程-培训课程-腾讯课堂
TypeScript 中文手册

上一篇 下一篇

猜你喜欢

热点阅读