美文网首页
TypeScript学习4、接口interface

TypeScript学习4、接口interface

作者: 喜欢骑着蜗牛散步 | 来源:发表于2019-10-18 17:09 被阅读0次

接口interface
TypeScript的核心原则之一是对值所具有的结构进行类型检查,
接口的作用就是为我们的代码定义一些结构,其他人或者自己在使用这些工具或者函数时,遵循这个结构。

/* 基本用法*/
使用interface关键字定义
readonly : 只读属性(接口定义中属性前面加readonly,在数组中同样起作用)
? :可选属性(接口定义中属性后面加“?”)。


对象类型接口

interface NameInfo {
    readonly  firstName: string, // 只读
    lastName: string,
    age?: number, // 可选
}
// 使用接口
function getFullName({firstName, lastName, age}: NameInfo): string {
    const str = `${firstName} ${lastName} ${age ? (age + ' years old') : ''}`
    return str
}
// 只传两个参数调用
let param: NameInfo = {
    firstName: 'WANG',
    lastName: 'ZHI',
}
// param.firstName = 'ZHANG' // 报错, 只读属性不可修改
param.lastName = 'CHAO'
console.log(getFullName(param))// WANG CHAO

// 所有参数传入调用
let param1: NameInfo = {
    firstName: 'WANG',
    lastName: 'CHAO',
    age: 18,
}
console.log(getFullName(param1))// WANG CHAO 18 years old

索引类型接口
支持两种索引签名:字符串和数字。 可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 number来索引时,JavaScript会将它转换成string然后再去索引对象。

interface IArray {
    [index: number]: string, //数字索引
  }
 let iArr: IArray= ["WANG", "CHAO"];
 let ant: string = iArr[0];
 interface IString {
    [propName: string]: string, //字符串索引
  }

有的时候在使用接口的时候,只能访问接口的属性,但是这个时候是不够用的。这个时候要怎么办呢。

interface NameInfo {
    readonly  firstName: string, // 只读
    lastName: string,
    age?: number, // 可选
}
getFullName({
     firstName: 'WANG',
     lastName: 'CHAO',
     age: 18,
     sex:20 // 因为多传了一个参数所以报错 ERROR in interface.ts(50,5)TS2345: Argument of type '{ firstName: string; lastName: string; age: number; sex: number; }' is not assignable to parameter of type 'NameInfo'.Object literal may only specify known properties, and 'sex' does not exist in type 'NameInfo'.
 })

解决办法1:类型断言 ,告诉编译器,我传入的参数就是NameInfo类型的。

getFullName({
    firstName: 'WANG',
    lastName: 'CHAO',
    age: 18,
    sex:20 
} as NameInfo)

解决办法2: 字符串索引签名, 在接口中写入 [propName:string]: any 。

interface NameInfo {
    readonly  firstName: string, // 只读
    lastName: string,
    age?: number, // 可选
    [propName:string]: any
}
function getFullName({firstName, lastName, age}: NameInfo): string {
    const str = `${firstName} ${lastName} ${age ? (age + ' years old') : ''}`
    return str
}
getFullName({
    firstName: 'WANG',
    lastName: 'CHAO',
    age: 18,
    sex:20 
})

数组结构接口(用法和定义对象结构相同)。

interface ArrInfo{
    readonly 0:string,
    1?:number,
    [propsName: string]: any
}
let arr1: ArrInfo = ['w',5,true,false]

函数结构接口 (用法和定义对象结构相同。

interface AddFun {
    (firstName: string, age?:number): string 
}
let add: AddFun = (f, a) => `${f}${(a ? a: '')}`

console.log(add('WANG'))// WANG
console.log(add('WANG', 18))// WANG18

接口继承 :提高接口复用性。
使用extends关键字继承。

interface Animal{
    color:string
}
interface Dog extends Animal{
    age:number
}

interface Cat {
    age:number
}
// DOG接口 继承了 Animal接口所以有了color属性的限定。
let dog: Dog = {
    color :'red',
    age: 2
}
let cat: Cat = {
    age: 3
}

混合类型接口:一个接口,既可以定义一个函数,也可以像对象一样拥有属性和方法。

interface AddCount {
    (): number; // 函数AddCount,无参数,返回值是number类型
    count: number;// 为它规定属性count
    reset(): void;// 为它规定方法reset
}
const addCountFunc = (): AddCount => {
    const a  = () =>{
        return a.count ++
    }
    a.count = 0;
    a.reset = () =>{
        a.count = 0;
    }
    return a
}

let a = addCountFunc()
console.log(a())// 0
console.log(a())// 1
console.log(a())// 2
a.reset()// 重置count
console.log(a())// 0

implements 类类型接口

使用接口可以强制一个类的定义必须包含哪些内容,类类型接口检测该接口定义的类的实例,所以使用static修饰符会抛出错误。

interface FootInterface {
    type: string
    eat(): void;
}
class  FootClass implements FootInterface {
    public  type: string
    constructor(type: string) {
        this.type = type
    }
    public eat() {

    }
}

接口继承类

当接口继承了一个类类型时,它会继承类的成员但不包括其实现。 就好像接口声明了所有类中存在的成员,但并没有提供具体实现一样。
接口同样会继承到类的private和protected成员。 这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时,这个接口类型只能被这个类或其子类所实现(implement)

class B {
    private type: string
}
interface I extends B {}
class C extends B implements I {
    public name: string
}

相关文章

网友评论

      本文标题:TypeScript学习4、接口interface

      本文链接:https://www.haomeiwen.com/subject/qdcwmctx.html