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) // 使用映射中的值}}
}