概述

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. 如何在window server IIS上部署可以使用web deploy?

    环境: windows server2012 方式1: 1,下载"wpilauncher.exe" Web平台安装程序.下载地址:http://www.microsoft.com/ ...

  2. python中的sort方法

    Python中的sort()方法用于数组排序,本文以实例形式对此加以详细说明: 一.基本形式 列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不 ...

  3. DotNetOpenAuth 使用指南

    这几天一直在研究DotNetOpenAuth,源码处处是坑啊!写此文只为大家更顺利掌握DotNetOpenAuth使用方法,尽量少走弯路. 说明一下:我的环境是Win7 64   VS2015 upd ...

  4. Head First Python学习笔记3——持久存储

    经过上几章的学习,完成如下任务:读取一个文本文件里的内容,将每一行的内容按“:”分割成两部分,根据分割出第一项判断并分别放入两个列表里,去除首尾空白,在屏幕上打印. # 两个列表用于存储数据man=[ ...

  5. JavaScript pop()函数弹出数组最后数据

    改变数组中数据的另一种方法是用 .pop() 函数. .pop() 函数用来“抛出”一个数组末尾的值.我们可以把这个“抛出”的值赋给一个变量存储起来. 数组中任何类型的数据条目(数值,字符串,甚至是数 ...

  6. 什么是memcached?

    缓存是一种常驻与内存的内存数据库,内存的读取速度远远快于程序在磁盘读取数据的速度.我们在设计程序的时候常常会考虑使用缓存,将经常访问的数据放到内存上面这样可以提高访问数据的速度,同时可以降低磁盘或数据 ...

  7. 不用中间变量,交换a、b值

    如果要交换a.b之间的值,一般的做法是: tmp=a;a=b;b=tmp;这种方法不得不使用一个临时变量. 从网上学来一个方法,可以不用使用临时变量: a^=b^=a^=b; 这样计算之后,就可以交换 ...

  8. dubbo的重试机制

    对dubbo熟悉的人对下面的配置一定不会陌生: <dubbo:reference id="xxxx" interface="xx" check=" ...

  9. springboot面试专题及答案

    声明:此文章非本人所 原创,是别人分享所得,如有知道原作者是谁可以联系本人,如有转载请加上此段话 问题一 什么是 Spring Boot? 多年来,随着新功能的增加,spring 变得越来越复杂.只需 ...

  10. 第二节:Java开发环境的搭建

    一.认识并安装JDK 1.JDK(Java Development Kit)是Java开发工具集,包括Java运行环境(JRE).Java开发工具以及一些基础类库,进行Java开发所必须安装的软件. ...