鸿蒙ArkTS:接口(interface)

接口概念

“接口”是一种定义类型结构的方法,它描述了一个类型应该具有的属性、方法和索引签名。

接口的基本定义

接口允许你定义一个类型应该有的结构。这种结构可以包括:

  • 属性(Properties):描述对象应该拥有的字段。
  • 方法(Methods):描述对象应该能够执行的行为。
  • 索引签名(Index Signatures):允许你定义对象如何通过索引访问其成员。
  • 可选属性(Optional Properties):通过在属性名后添加 ? 符号来标记属性为可选。
  • 只读属性(Readonly Properties):通过在属性前添加 readonly 关键字来定义不可修改的属性。

接口的语法

interface InterfaceName {
  // 属性
  property: Type;
  // 方法
  method(arg1: Type, arg2: Type): ReturnType;
}

接口的应用

接口可以应用于多种场景,例如:

  1. :类可以实现一个或多个接口,确保类具备某些特定的结构。
  2. 对象字面量:可以用接口来验证一个对象字面量是否具有预期的结构。
  3. 函数参数:接口可以用来定义函数参数的结构。
  4. 泛型约束:接口可以用来定义泛型函数或类的参数类型约束。
    interface arrLength {
      length: number
    }
    
    function arrLengthFun<t extends arrLength>(params: t): t {
      return params
    }
    
    console.log('arrLengthFun', arrLengthFun([1, 2, 3, 4, 6]).length);

接口继承

接口之间也可以进行继承,一个接口可以从另一个接口继承属性和方法:

interface Shape {
  color: string;
}

interface Square extends Shape {
  length: number;
}

const square: Square = { color: "blue", length: 10 };

接口实现implements

通过接口集合implements来限制类,必须要有的某些属性和方法。

interface CanEat {
  eat(food: string): void;
}

class Animal implements CanEat {
  eat(food: string): void {
    return food
  }
}

const animal = new Animal();
animal.eat("grass");

泛型接口

泛型接口允许你在接口定义中使用泛型参数,使得接口可以根据不同的类型参数来适应不同的类型需求。

interface GenericInterface<T> {
  value: T;
}

// 使用泛型接口
const obj: GenericInterface<string> = { value: "hello" };
interface Food<T> {
  id: (value: T) => T
  idArr: () => T[]
}

let foodFun: Food<number> = {
  id(value: number) {
    return value
  },
  idArr() {
    return [1, 2, 3]
  }
}
console.log('foodFun',foodFun.id(111))
console.log('foodFun',foodFun.idArr())
interface GenericFunction<T, R> {
  process: (value: T) => R;
}

class DataProcessor implements GenericFunction<number, string> {
  process(value: number): string {
    return value.toString();
  }
}

const processor: GenericFunction<number, string> = new DataProcessor();
console.log(processor.process(123)); // 输出 "123"

充盈美满

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值