Record<string, string>
在鸿蒙 App 开发中的用法
在 TypeScript 中,Record<string, string>
是一个映射类型(Mapped Type),用于描述一个对象的结构。在鸿蒙 App 开发中,它常用于定义接口、组件属性或函数参数的类型约束。
1. 基本含义
Record<K, V>
表示一个对象:
- 键(Key) 的类型为
K
- 值(Value) 的类型为
V
例如,Record<string, string>
表示一个字符串键到字符串值的映射:
typescript
const obj: Record<string, string> = {
name: 'John',
age: '30', // 值必须是字符串
// 可以添加任意数量的字符串键值对
};
2. 在鸿蒙开发中的常见用法
2.1 定义组件属性类型
typescript
import { Component, Prop } from '@ohos/hiviewdfx';
@Component
struct MyComponent {
// 接收一个字符串到字符串的映射
@Prop messageMap: Record<string, string> = {
success: '操作成功',
error: '发生错误'
};
build() {
Column() {
Text(this.messageMap.success) // 使用映射中的值
}
}
}