1# \@Type装饰器:标记类属性的类型
2
3为了实现序列化类时不丢失属性的复杂类型,开发者可以使用\@Type装饰器装饰类属性。
4
5
6\@Type的目的是标记类属性,配合PersistenceV2使用,防止序列化时类丢失。在阅读本文档前,建议提前阅读:[PersistenceV2](./arkts-new-persistencev2.md)。
7
8>**说明:**
9>
10>\@Type从API version 12开始支持。
11>
12
13
14## 概述
15
16\@Type标记类属性,使得类属性序列化时不丢失类型信息,便于类的反序列化。
17
18
19## 装饰器说明
20
21| \@Type装饰器 | 说明 |
22| ------------------- | ------------------------------------------------------------ |
23| 装饰器参数 | type:类型。 |
24| 可装饰的类型 | Object class以及Array、Date、Map、Set等内嵌类型。 |
25
26
27## 使用限制
28
291、只能用在\@ObservedV2装饰的类中,不能用在自定义组件中;
30
31```ts
32class Sample {
33  data: number = 0;
34}
35@ObservedV2
36class Info {
37  @Type(Sample)
38  @Trace sample: Sample = new Sample(); // 正确用法
39}
40@Observed
41class Info2 {
42  @Type(Sample)
43  sample: Sample = new Sample(); // 错误用法,不能用在@Observed装饰的类中,编译时报错
44}
45@ComponentV2
46struct Index {
47  @Type(Sample)
48  sample: Sample = new Sample(); // 错误用法,不能用在自定义组件中
49  build() {
50  }
51}
52```
53
542、不支持collections.Setcollections.Map等类型;
55
563、不支持非buildin类型,如PixelMap、NativePointer、ArrayList等Native类型;
57
584、不支持简单类型,如string、number、boolean等。
59
60## 使用场景
61
62### 持久化数据
63
64数据页面
65```ts
66import { Type } from '@kit.ArkUI';
67
68// 数据中心
69@ObservedV2
70class SampleChild {
71  @Trace p1: number = 0;
72  p2: number = 10;
73}
74
75@ObservedV2
76export class Sample {
77  // 对于复杂对象需要@Type修饰,确保序列化成功
78  @Type(SampleChild)
79  @Trace f: SampleChild = new SampleChild();
80}
81```
82
83页面
84```ts
85import { PersistenceV2 } from '@kit.ArkUI';
86import { Sample } from '../Sample';
87
88@Entry
89@ComponentV2
90struct Page {
91  prop: Sample = PersistenceV2.connect(Sample, () => new Sample())!;
92
93  build() {
94    Column() {
95      Text(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`)
96        .fontSize(30)
97        .onClick(() => {
98          this.prop.f.p1++;
99        })
100    }
101  }
102}
103```
104