1# \@Type Decorator: Marking the Types of the Class Property
2
3To avoid losing complex types of the properties when serializing classes, you can use the \@Type Decorator to decorate class.
4
5
6\@Type is used to mark class properties. Used together with **PersistenceV2**, \@Type can prevent class loss during serialization. Before reading this topic, you are advised to read [PersistenceV2](./arkts-new-persistencev2.md).
7
8>**NOTE**
9>
10>\@Type is supported since API version 12.
11>
12
13
14## Overview
15
16\@Type marks class properties to avoid losing type information during class property serialization, facilitating class deserialization.
17
18
19## Decorator Description
20
21| \@Type Decorator| Description|
22| ------------------- | ------------------------------------------------------------ |
23| Parameter| Type.|
24| Allowed type| Object class and embedded types such as Array, Date, Map, and Set.|
25
26
27## Constraints
28
291. \@Type can be used only in classes decorated by \@ObservedV2 and cannot be used in custom components.
30
31```ts
32class Sample {
33  data: number = 0;
34}
35@ObservedV2
36class Info {
37  @Type(Sample)
38  @Trace sample: Sample = new Sample(); // Correct usage.
39}
40@Observed
41class Info2 {
42  @Type(Sample)
43  sample: Sample = new Sample(); // Incorrect usage. @Type cannot be used in the @Observed decorated class. Otherwise, an error is reported during compilation.
44}
45@ComponentV2
46struct Index {
47  @Type(Sample)
48  sample: Sample = new Sample(); // Incorrect usage. @Type cannot be used in the custom component.
49  build() {
50  }
51}
52```
53
542. Types such as collections.Set and collections.Map are not supported.
55
563. Non-buildin types, such as native PixelMap, NativePointer, and ArrayList types, are not supported.
57
584. Simple types such as string, number, and boolean, are not supported.
59
60## When to Use
61
62### Saving Data for Persistence
63
64Data page
65```ts
66import { Type } from '@kit.ArkUI';
67
68// Data center
69@ObservedV2
70class SampleChild {
71  @Trace p1: number = 0;
72  p2: number = 10;
73}
74
75@ObservedV2
76export class Sample {
77  // Complex objects need to be decorated by @Type to ensure successful serialization.
78  @Type(SampleChild)
79  @Trace f: SampleChild = new SampleChild();
80}
81```
82
83Page
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