概述

typescript 的接口只会关注值的外形,实际就是类型(条件)的检查,只要满足就是被允许的。

接口描述了类的公共部分。

接口

interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
var user = {
firstName: 'Jane',
lastName: 'User'
};
document.body.innerHTML = greeter(user); // 可选属性
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = { color: 'white', area: 100 };
if ( config.width ) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: 'black'}); // 只读属性(只能在对象刚刚创建的时候修改其值)
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error // ReadonlyArray<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
// 可以使用断言重写
a = ro as number[]; // const vs readonly
// 作为变量则用 const
// 作为属性则使用 readonly // 对于会额外带有任意数量的其他属性,最佳方法是添加一个字符串索引签名
// 一旦定义了任意属性,那么确定属性和可选属性都必须是它的子属性,如下代码,即string、number为any的子属性
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any; // 字符串索引签名
}

接口(函数类型)

interface SearchFunc {
// 定义调用签名
(source: string, subString: string): boolean;
} let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
if ( result == -1 ) {
return false;
} else {
return true;
}
}
// 对于函数类型的类型检查,函数的参数名不需要与接口定义的名字相匹配,但是要求对应位置上的参数类型是兼容的。

接口(可索引的类型)

// 当用 number 去索引 StringArray 时会得到 string 类型的返回值
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ['Bob', 'Fred'];
let myStr: string = myArray[0]; // 防止给索引赋值
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ['Alice', 'Bob'];
myArray[2] = 'Mallory'; // error // 确保所有属性与其返回值类型相匹配
interface NumberDictionary {
[index: string]: number;
length: number;
name: string; // 错误,name的类型不是索引类型的子类型
}

类类型

// 强制一个类去符合某种契约
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
} // 在接口中描述一个方法,在类中实现它
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
} // 类静态部分与实例部分的区别
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
} function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new cotr(hour, minute);
} class DigitalClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() {
console.log('beep beep');
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() {
console.log('tick tock');
}
} let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

扩展接口

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

interface Shape {
color: string;
} interface Square extends Shape {
sideLength: number;
} let square = <Square>{};
square.color = 'blue';
square.sideLength = 10; // 继承多个接口
interface Shape {
color: string;
} interface PenStroke {
penWidth: number;
} interface Square extends Shape, PenStroke {
sideLength: number;
} let square = <Square>{};
square.color = 'blue';
square.sideLength = 10;
square.penWidth = 5.0;

混合类型

// 一个对象可以同时做为函数和对象使用,并带有额外的属性
interface Counter {
(start: number): string;
interval: number;
reset(): void;
} function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function() { };
return counter;
} let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

接口继承类

当接口继承类类型时,它会继承类的成员但不包括其实现。接口同样会继承到类的private和protected成员。意味着这个接口只能被这个类或其子类所实现。

class Control {
private state: any;
} interface SelectableControl extends Control {
select(): void;
} class Button extends Control {
select() { }
} class TextBox extends Control {
select() { }
} class Image {
select() { }
} class Location {
select() { }
}

Typescript 接口(interface)的更多相关文章

  1. typescript接口---interface

    假如我现在需要批量生产一批对象,这些对象有相同的属性,并且对应属性值的数据类型一致.该怎么去做? 在ts中,因为要检验数据类型,所以必须对每个变量进行规范,自然也提供了一种批量规范的功能.这个功能就是 ...

  2. typescript 接口 interface

    代码: // 接口:行为的抽象 // 一.对class类的约束 // 接口定义 // 打印机 interface Iprinter { Printing(msg:string):string; } i ...

  3. TypeScript学习指南第二章--接口(Interface)

    接口(Interface) TypeScript的核心机制之一在于它的类型检查系统(type-checker)只关注一个变量的"模型(shape)" 稍后我们去了解这个所谓的形状是 ...

  4. 从C#到TypeScript - 接口

    总目录 从C#到TypeScript - 类型 从C#到TypeScript - 高级类型 从C#到TypeScript - 变量 从C#到TypeScript - 接口 从C#到TypeScript ...

  5. typescript接口的概念 以及属性类型接口

    /* 1.vscode配置自动编译 1.第一步 tsc --inti 生成tsconfig.json 改 "outDir": "./js", 2.第二步 任务 ...

  6. 【区分】Typescript 中 interface 和 type

    在接触 ts 相关代码的过程中,总能看到 interface 和 type 的身影.只记得,曾经遇到 type 时不懂查阅过,记得他们很像,相同的功能用哪一个都可以实现.但最近总看到他们,就想深入的了 ...

  7. 《三》大话 Typescript 接口

    > 前言: 本文章为 TypeScript 系列文章. 旨在利用碎片时间快速入门 Typescript. 或重新温故 Typescript 查漏补缺.在官方 api 的基础上, 加上一些日常使用 ...

  8. typescript接口扩展

    /* typeScript中的接口 接口扩展 */ /* 接口的作用:在面向对象的编程中,接口是一种规范的定义,它定义了行为和动作的规范,在程序设计里面,接口起到一种限制和规范的作用.接口定义了某一批 ...

  9. TypeScript接口与类的使用

    一.TypeScript接口 Interfaces 可以约定一个对象的结构 一个对象去实现一个接口 就必须拥有这个接口中所有的成员用interface定义接口, 并且定义接口中成员的类型 编译之后会发 ...

随机推荐

  1. Java之IO(七)ObjectInputStream和ObjectOutputStream

    转载请注明源出处:http://www.cnblogs.com/lighten/p/7003536.html 1.前言 本章介绍Java字节流中重要的成员,对象流ObjectInputStream和O ...

  2. linux传输文件命令: rz 和 sz

    参考: https://www.cnblogs.com/xiluhua/p/6218563.html https://blog.csdn.net/u014242496/article/details/ ...

  3. SPSS学习系列之SPSS Modeler的帮助文档怎么调出来使用?

    不多说,直接上干货! 欢迎大家,加入我的微信公众号:大数据躺过的坑        人工智能躺过的坑       同时,大家可以关注我的个人博客:    http://www.cnblogs.com/z ...

  4. Struts动态表单(DynamicForm)

    动态表单的含义是不要手动定义,直接在配置文件中进行定义. 1.手动进行定义 <form-beans > <form-bean name="userForm" ty ...

  5. springboot-4-整合fastjson

    使用fastjson作为springboot的默认json解析, 原来使用的是jackson 1, 引入依赖 <dependencies> <dependency> <g ...

  6. 用ruby调用执行shell命令

    碰到需要调用操作系统shell命令的时候,Ruby为我们提供了六种完成任务的方法: 1.Exec方法:     Kernel#exec方法通过调用指定的命令取代当前进程:   例子:       $ ...

  7. C#中的序列化和反序列化是什么、有什么作用、使用方法详解

    什么是序列化与反序列化??? 序列化和反序列化,我们可能经常会听到,其实通俗一点的解释,序列化就是把一个对象保存到一个文件或数据库字段中去,反序列化就是在适当的时候把这个文件再转化成原来的对象使用. ...

  8. [转]微信小程序之购物车 —— 微信小程序实战商城系列(5)

    本文转自:http://blog.csdn.net/michael_ouyang/article/details/70755892 续上一篇的文章:微信小程序之商品属性分类  —— 微信小程序实战商城 ...

  9. javascript加上标签

    在javascript脚本中可以加上标签,方便javascript程序进行快速定位,标签一般由一个合法的字符名称加上一个冒号组成,标签可以放在任意行的位置,这样可以为该行设置一个标记,然后再 结构体中 ...

  10. Jquery Easy UI初步学习(三)数据增删改

    第二篇只是学了加载用datagrid加载数据,数据的增删改还没有做,今天主要是解决这个问题了. 在做增删改前需要弹出对应窗口,这就需要了解一下EasyUi的弹窗控件. 摘自:http://philoo ...