HarmonyOS鸿蒙Next中如何获取数组的类型?

HarmonyOS鸿蒙Next中如何获取数组的类型?

5 回复

可以通过 typeof 运算符来获取类型,返回的是一个字符串。

// 后面跟上需要获取类型的 数据或变量 即可
typeof 表达式
console.log(typeof [1, 2, 3]) // object

更多关于HarmonyOS鸿蒙Next中如何获取数组的类型?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


基础类型数组检测

function getArrayType(arr: any[]): string {
  if (arr.length === 0) return 'unknown'
  
  const firstType = typeof arr
  for (const item of arr) {
    if (typeof item !== firstType) {
      return 'mixed'
    }
  }
  return `${firstType}[]` // 返回类似"string[]"的结果
}

对象类型数组检测

// 检测自定义类型数组
class Person {
  name: string = ''
}

const people: Person[] = [new Person(), new Person()]

if (people instanceof Person) {
  console.log('Person数组类型') 
}

获取数组类型,可以使用typeof获取,可以参考以下代码:

let arr = [1,2,'str']
let type = typeof arr; // 
console.log(type) // 此时type 是object

let type1 = typeof arr[1]; // 判断索引1值的类型
console.log(type1) // 此时type 是object

let type2 = typeof arr[2]; // 判断索引2值的类型
console.log(type2) // 此时type 是object

在HarmonyOS Next中,使用TypeScript/ArkTS开发时,可以通过Array.isArray()方法判断是否为数组。要获取数组元素类型,可以使用泛型或类型推断:

  1. 显式类型标注:
let arr: Array<number> = [1, 2, 3];
// 元素类型即为number
  1. 使用typeof推断:
const strArr = ['a', 'b'];
type ElementType = typeof strArr[0]; // 类型为string
  1. 对于对象数组,可通过接口定义类型:
interface User {
  name: string;
}
let users: User[] = [{name: 'Alice'}];

注意:ArkTS是静态类型语言,类型信息在编译期确定。

在HarmonyOS Next中,可以通过TypeScript的类型推断和typeof操作符来获取数组的类型。以下是几种常见方法:

  1. 使用typeof获取数组实例的类型:
const arr = [1, 2, 3];
type ArrType = typeof arr;  // number[]
  1. 获取数组元素类型:
type ElementType = ArrType[number];  // number
  1. 对于泛型数组,可以使用infer提取元素类型:
type GetElementType<T> = T extends Array<infer U> ? U : never;
type NumType = GetElementType<number[]>;  // number
  1. 使用ArkTS的泛型约束:
function getArrayType<T>(arr: Array<T>): T {
    return arr[0];
}
// 调用时会自动推断出T的类型

这些方法在HarmonyOS Next的开发中都适用,可以根据具体场景选择合适的方式。

回到顶部