TypeScript笔记:接口

1 介绍

接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,

interface interface_name { 
}

接口不能转换为 JavaScript。 它只是 TypeScript 的一部分 

2 举例

interface IPerson { 
    firstName:string, 
    lastName:string, 
    sayHi: ()=>string 
} 
 
var customer:IPerson = { 
    firstName:"Tom",
    lastName:"Hanks", 
    sayHi: ():string =>{return "Hi there"} 
} 
 
console.log("Customer 对象 ") 
console.log(customer.firstName) 
console.log(customer.lastName) 
console.log(customer.sayHi())  
/*
Customer 对象
Tom
Hanks
Hi there
*/
 
var employee:IPerson = { 
    firstName:"Jim",
    lastName:"Blakes", 
    sayHi: ():string =>{return "Hello!!!"} 
} 
 
console.log("Employee  对象 ") 
console.log(employee.firstName) 
console.log(employee.lastName)
/*
Employee  对象
Jim
Blakes
*/

3 使用联合类型的接口

interface RunOptions { 
    program:string; 
    commandline:string[]|string|(()=>string); 
} 
//commandline 可以是一个string,可以是一个string数组,可以是没有输入参数、输出为string的函数
 
// commandline 是字符串
var options:RunOptions = {program:"test1",commandline:"Hello"}; 
console.log(options.commandline)  
 
// commandline 是字符串数组
options = {program:"test1",commandline:["Hello","World"]}; 
console.log(options.commandline[0]); 
console.log(options.commandline[1]);  
 
// commandline 是一个函数表达式
options = {program:"test1",commandline:()=>{return "**Hello World**";}}; 
 
var fn:any = options.commandline; 
console.log(fn());

4 接口的继承

接口可以通过其他接口来扩展自己

Typescript 允许接口继承多个接口

Child_interface_name extends super_interface_name

Child_interface_name extends super_interface1_name, super_interface2_name,…,super_interfaceN_name
interface Person { 
   age:number 
} 
 
interface Musician extends Person { 
   instrument:string 
} 
 
var drummer = {}; 
drummer.age = 27 
drummer.instrument = "Drums" 
console.log("年龄:  "+drummer.age)
console.log("喜欢的乐器:  "+drummer.instrument)
/*
年龄:  27
喜欢的乐器:  Drums
*/

5 多继承示例

interface IParent1 { 
    v1:number 
} 
 
interface IParent2 { 
    v2:number 
} 
 
interface Child extends IParent1, IParent2 { } 
var Iobj:Child = { v1:12, v2:23} 
console.log("value 1: "+Iobj.v1+" value 2: "+Iobj.v2)
//value 1: 12 value 2: 23

你可能感兴趣的:(Typescript,&,JavaScript,&,HTML,笔记)