interface

作者: JamesSawyer | 来源:发表于2021-07-28 16:57 被阅读0次

接口用于定义对象的 '轮廓'

interface IPerson {
  firstName: string;
}

function getName(person: IPerson) {
  return person.firstName;
}

const person = {
  firstName: 'James',
  age: 27
}

getName(person); // OK

但是如果我们直接传入一个对象字面量进去,ts就会报错, 因为ts对对象字面量检测更加严格, 对象字面量只能指定已知属性,'age' 没有定义

getName({firstName: 'James', age: 27});

可以通过下面这种方式来解决

interface IPerson {
  firstName: string;
  age?: number;
}

属性站位符

可以通过类似计算属性的方式来声明接口,表示未知属性名,这个属性默认是 可选属性

interface IPerson {
  firstName: string;
  age?: number;
  [propName: string]: any; // 此处有待深入
}

class 实现 接口

在传统的面向对象中,类继承或者说是是实现接口是很常见的, 使用 implements 关键字, 必填属性必须在class中声明

interface IPerson {
  firstName: string;
  age?: number;
  [propName: string]: any;
  greet(name: string): void;
}

class Student implements IPerson {
  firstName: string = 'James';
  greet(name: string) {
    console.log(`hello ${name}`);
  }
}

let p = new Student();

p.greet(p.firstName); // hello James

interface 和 Function type

可以通过接口来指定方法类型接口

interface IMulti {
  (num1: number, num2: number): number;
}

let square:IMulti = function(a: number, b: number) {
  return a * b;
}

接口扩展接口

一个接口可以 extends 另一个接口,也可以对扩展的接口进行override

interface IPerson {
  firstName: string;
  age?: number;
  [propName: string]: any;
  greet(name: string): void;
}

interface IStudent extends IPerson {
  study(gener: string): void;
  age: number; // override 将其变为必填属性
}

相关文章

  • interface{} 与 []interface{}

    简介 基于可以对interface{}赋值任何类型的变量,很多人会尝试如下的代码: 很不幸会导致错误: 于是问题来...

  • Interface

    Interface is a group of method signatures, continuin with...

  • Interface

    为什么interface中的变量都是static public final? 首先接口是一种高度抽象的"模版",,...

  • interface

    接口用于定义对象的 '轮廓' 但是如果我们直接传入一个对象字面量进去,ts就会报错, 因为ts对对象字面量检测更加...

  • interface

    http://blog.csdn.net/justaipanda/article/details/43155949...

  • @interface

    深入理解Java:注解(Annotation)自定义注解入门http://www.cnblogs.com/peid...

  • Interface

    4.1 Comma Separated Value. *Comma Separated Value *or CSV...

  • interface

    由于基础很差不太明白interface到底是个啥接口上我一直不太理解,插上就通电了......通电什么意思 插曲最...

  • interface

    java语言里面使用interface来声明一个接口,接口其实是一个特殊的抽象类,在接口里面的方法全部都是抽象的。...

  • @Interface

    1.@Retention:RetentionPolicy.SOURCE:检查,源文件存在,编译丢失Retentio...

网友评论

      本文标题:interface

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