Typescript 接口(interface)
概述
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)的更多相关文章
- typescript接口---interface
假如我现在需要批量生产一批对象,这些对象有相同的属性,并且对应属性值的数据类型一致.该怎么去做? 在ts中,因为要检验数据类型,所以必须对每个变量进行规范,自然也提供了一种批量规范的功能.这个功能就是 ...
- typescript 接口 interface
代码: // 接口:行为的抽象 // 一.对class类的约束 // 接口定义 // 打印机 interface Iprinter { Printing(msg:string):string; } i ...
- TypeScript学习指南第二章--接口(Interface)
接口(Interface) TypeScript的核心机制之一在于它的类型检查系统(type-checker)只关注一个变量的"模型(shape)" 稍后我们去了解这个所谓的形状是 ...
- 从C#到TypeScript - 接口
总目录 从C#到TypeScript - 类型 从C#到TypeScript - 高级类型 从C#到TypeScript - 变量 从C#到TypeScript - 接口 从C#到TypeScript ...
- typescript接口的概念 以及属性类型接口
/* 1.vscode配置自动编译 1.第一步 tsc --inti 生成tsconfig.json 改 "outDir": "./js", 2.第二步 任务 ...
- 【区分】Typescript 中 interface 和 type
在接触 ts 相关代码的过程中,总能看到 interface 和 type 的身影.只记得,曾经遇到 type 时不懂查阅过,记得他们很像,相同的功能用哪一个都可以实现.但最近总看到他们,就想深入的了 ...
- 《三》大话 Typescript 接口
> 前言: 本文章为 TypeScript 系列文章. 旨在利用碎片时间快速入门 Typescript. 或重新温故 Typescript 查漏补缺.在官方 api 的基础上, 加上一些日常使用 ...
- typescript接口扩展
/* typeScript中的接口 接口扩展 */ /* 接口的作用:在面向对象的编程中,接口是一种规范的定义,它定义了行为和动作的规范,在程序设计里面,接口起到一种限制和规范的作用.接口定义了某一批 ...
- TypeScript接口与类的使用
一.TypeScript接口 Interfaces 可以约定一个对象的结构 一个对象去实现一个接口 就必须拥有这个接口中所有的成员用interface定义接口, 并且定义接口中成员的类型 编译之后会发 ...
随机推荐
- C# 基元类型
C#编程中,初始化一个整数有两种方式: (1).较繁琐的方法,代码如下: Int32 a = new Int32(); (2).极简的方法,代码如下: ; 对比两种方法,分析如下: 第一种:过于繁琐, ...
- 用COS实现文件上传
cos是O'Rrilly公司开发的一款用于HTTP上传文件的OpenSource组件 需要cos.jar,下载地址:http://www.servlets.com/cos/ cos上传文件很简单,比f ...
- Linux的shell script
Linux的shell script //编辑shell: vi a.sh //子进程运行shell sh a.sh //主线程运行shell source a.sh 相关例子: #!/bin/bas ...
- leetcode--539. Minimum Time Difference
Given a list of -hour clock time points in "Hour:Minutes" format, find the minimum minutes ...
- springboot-mongodb的多数据源配置
pom.xml中引入mongodb的依赖 <dependency> <groupId>org.springframework.boot</groupId> < ...
- 笔记:css3伪选择器改变滚动条样式
现在我打开支持前缀-webkit-的浏览器,也就是说只要支持前缀为-webkit-的浏览器才有效果 <!doctype html> <html lang="en" ...
- css3的overflow-anchor
overflow-anchor属性使我们能够选择退出滚动锚定,这是一个浏览器特性,旨在允许内容在用户当前的DOM位置上加载,而不需要在内容完全加载后更改用户的位置. 为何要有这个属性? 滚动锚定是一种 ...
- C#byte类型
byte类型的范围是0~255转换为二进制是00000000~11111111 ---------------------------------------------------------- C ...
- mongodb自学
http://www.runoob.com/mongodb/mongodb-databases-documents-collections.html
- 封装framework注意点
1.新建一个framework过程: . 2.在工程内新建一些类,注意,使用xib时初始化必须要加上loadnib:,否则会造成xib无效(可能是因为没有加载) 如下: JFViewControlle ...