美文网首页
ts的interface特性

ts的interface特性

作者: 米诺zuo | 来源:发表于2022-03-09 10:45 被阅读0次

interface 定义Person结构 interface Person {}

interface Person {
  name: string;
  age: number;
  ping(ip: string): void;
}

type 定义Person结构 type Person = {}

type Person = {
  name: string;
  age: number;
  ping(ip: string): void;
}

使用Person 类型

let user: Person = {
  name:'max',
  age:34,
  ping(ip: string){
    console.log('hi, ip is' +ip);
  }
}
user.ping('102.101.122.22');
// output 
// [LOG]: "hi, ip is102.101.122.22" 

interface用于不同class之间的共有的属性和方法。使用implements,一个class可以实现多个接口,逗号拼接。

interface Greetable {
  name: string;
  greet(pharse: string): void;
}

class Person implements Greetable{
  name: string;
  age =  30;
  constructor(n: string){
    this.name = n;
  }
  greet(pharse: string) {
    console.log(pharse + ' ' + this.name)
  }
}

let user: Greetable = new Person('max')
user.greet('you are');
console.log(user)

output:

[LOG]: "you are max" 
[LOG]: Person: {
  "age": 30,
  "name": "max"
} 

readonly 可以在interface中使用。
public, private不能在interface中使用。error: 'public' modifier cannot appear on a type member.

interface 可以通过 extends 继承另一个interface

interface Named {
  name: string;
}
interface Greetable extends Named {
  greet(pharse: string): void;
}

使用interface 的定义 function Type

// type AddFn = (a: number, b:number) => number;
interface AddFn {
  (a: number, b:number): number;
}
let  add: AddFn;
add = (n1:number, n2:number) => {
  return n1 + n2
}

interface 使用?定义可选参数

interface AddFn{
  name?: string;
  greet?(): number;
}

interface 编译成js没有任何输出,在js里面没有,ts里特有的。

相关文章

  • ts的interface特性

    interface 定义Person结构 interface Person {} type 定义Person结构...

  • typeScript语法

    ts类型 ts联合类型使用或 ts定义任意类型any ts定义函数返回值的类型 ts中的类定义 interface接口

  • TS的.d.ts和declare

    一、.d.ts d.ts文件是ts用来声明变量,模块,type,interface等等的,那在这种后缀的ts文件声...

  • angular中的核心概念

    组件 指令 服务 依赖注入 模块 ts中interface与class的区别 interface -- 接口只声明...

  • ts接口 interface

    概念:可以用来约束一个函数,对象,以及类的结构和类型 1.对象类型的接口 2.函数类型的接口 3.混合类型的接口(...

  • typescript 基本语法详解

    1、.d.ts是干嘛的 .d.ts文件是ts用来声明变量,模块,type,interface等等,声明变量之后,在...

  • TypeScript type 和 interface区别使用总

    在使用ts的type 和 interface时 两者作用(简单案例) interface只能定义对象数据结构类型。...

  • angluar学习笔记基本操作

    新建 typescript interface笔记app.component.ts app.component.h...

  • typescript中type和interface区别

    在ts中,定义类型由两种方式:接口(interface)和类型别名(type alias)interface只能定...

  • interface{} 接口类型

    interface定义 interface(接口)是golang最重要的特性之一,Interface类型可以定义一...

网友评论

      本文标题:ts的interface特性

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