0
# Type Definitions & Interfaces
1
2
Comprehensive type definitions and interfaces that define the contracts and data structures for the Taro runtime system, providing type safety for cross-platform development.
3
4
## Overview
5
6
The type system provides complete TypeScript definitions for:
7
8
- **Instance Types**: App, page, and component instance interfaces
9
- **Event Types**: Event objects and event handling contracts
10
- **DOM Types**: Node, element, and document type definitions
11
- **Update Types**: Data structures for DOM updates and hydration
12
- **Lifecycle Types**: Component and page lifecycle method definitions
13
- **Configuration Types**: Page and component configuration interfaces
14
- **Platform Types**: Mini-program and web platform abstractions
15
16
## Instance Type Definitions
17
18
### Core Instance Types
19
20
```typescript { .api }
21
// Base component interface
22
interface Component<T = Record<string, any>> {
23
data?: T
24
setData?(data: Partial<T>, callback?: () => void): void
25
$component?: any
26
[key: string]: any
27
}
28
29
// Page lifecycle interface
30
interface PageLifeCycle {
31
onLoad?(options: Record<string, unknown>): void
32
onShow?(): void
33
onHide?(): void
34
onReady?(): void
35
onUnload?(): void
36
onPullDownRefresh?(): void
37
onReachBottom?(): void
38
onPageScroll?(event: { scrollTop: number }): void
39
onShareAppMessage?(event: any): any
40
onShareTimeline?(): any
41
onTabItemTap?(event: { index: number, pagePath: string, text: string }): void
42
onResize?(event: { size: { windowWidth: number, windowHeight: number } }): void
43
}
44
45
// Show/hide lifecycle
46
interface Show {
47
onShow?(): void
48
onHide?(): void
49
}
50
```
51
52
### Application Instance Types
53
54
```typescript { .api }
55
// Base app instance
56
interface AppInstance extends Show {
57
onLaunch?(options: any): void
58
onError?(error: string): void
59
globalData?: Record<string, any>
60
[key: string]: any
61
}
62
63
// React app instance
64
interface ReactAppInstance<T = AppInstance> extends Component<T>, AppInstance {
65
componentDidShow?(): void
66
componentDidHide?(): void
67
componentDidCatchError?(error: string): void
68
}
69
```
70
71
#### Usage Examples
72
73
```typescript
74
// App implementation
75
class MyApp implements ReactAppInstance {
76
globalData = {
77
userInfo: null,
78
settings: {}
79
}
80
81
onLaunch(options: any) {
82
console.log('App launched with options:', options)
83
this.initializeApp()
84
}
85
86
onShow() {
87
console.log('App became active')
88
}
89
90
onHide() {
91
console.log('App went to background')
92
}
93
94
onError(error: string) {
95
console.error('App error:', error)
96
this.reportError(error)
97
}
98
99
// React lifecycle integration
100
componentDidShow() {
101
// React-specific show handling
102
}
103
104
componentDidHide() {
105
// React-specific hide handling
106
}
107
108
private initializeApp() { /* ... */ }
109
private reportError(error: string) { /* ... */ }
110
}
111
```
112
113
### Page Instance Types
114
115
```typescript { .api }
116
// Base page instance
117
interface PageInstance extends PageLifeCycle {
118
route?: string
119
options?: Record<string, unknown>
120
data?: Record<string, any>
121
setData?(data: Record<string, any>, callback?: () => void): void
122
}
123
124
// React page instance
125
interface ReactPageInstance<T = PageProps> extends Component<T>, PageInstance {
126
// React component properties
127
props?: T
128
state?: any
129
setState?(updater: any, callback?: () => void): void
130
131
// React lifecycle methods
132
componentDidMount?(): void
133
componentWillUnmount?(): void
134
componentDidUpdate?(): void
135
136
// Mini-program lifecycle integration
137
componentDidShow?(): void
138
componentDidHide?(): void
139
}
140
141
// Page props interface
142
interface PageProps {
143
tid?: string
144
[key: string]: any
145
}
146
```
147
148
#### Usage Examples
149
150
```typescript
151
// Page implementation
152
interface HomePageState {
153
userInfo: User | null
154
loading: boolean
155
posts: Post[]
156
}
157
158
class HomePage implements ReactPageInstance<PageProps> {
159
state: HomePageState = {
160
userInfo: null,
161
loading: false,
162
posts: []
163
}
164
165
// Mini-program lifecycle
166
onLoad(options: Record<string, unknown>) {
167
console.log('Page loaded with options:', options)
168
this.loadInitialData()
169
}
170
171
onShow() {
172
console.log('Page shown')
173
this.refreshUserStatus()
174
}
175
176
onReady() {
177
console.log('Page ready for interaction')
178
}
179
180
onPullDownRefresh() {
181
this.refreshData().then(() => {
182
wx.stopPullDownRefresh()
183
})
184
}
185
186
onReachBottom() {
187
if (!this.state.loading) {
188
this.loadMorePosts()
189
}
190
}
191
192
onShareAppMessage() {
193
return {
194
title: 'Check out these posts',
195
path: '/pages/home/home'
196
}
197
}
198
199
// React lifecycle
200
componentDidMount() {
201
// React-specific initialization
202
}
203
204
componentWillUnmount() {
205
// Cleanup
206
}
207
208
// React integration
209
componentDidShow() {
210
// Called from onShow
211
}
212
213
componentDidHide() {
214
// Called from onHide
215
}
216
217
private async loadInitialData() { /* ... */ }
218
private async refreshData() { /* ... */ }
219
private async loadMorePosts() { /* ... */ }
220
private refreshUserStatus() { /* ... */ }
221
}
222
```
223
224
### Generic Instance Type
225
226
```typescript { .api }
227
// Universal instance interface
228
interface Instance<T = Record<string, any>> extends Component<T>, Show, PageInstance {
229
// Combines all instance capabilities
230
}
231
```
232
233
## Event Type Definitions
234
235
### Core Event Types
236
237
```typescript { .api }
238
// Mini-program event structure
239
interface MpEvent {
240
type: string
241
timeStamp: number
242
target: {
243
id: string
244
dataset: Record<string, any>
245
[key: string]: any
246
}
247
currentTarget: {
248
id: string
249
dataset: Record<string, any>
250
[key: string]: any
251
}
252
detail?: any
253
touches?: Touch[]
254
changedTouches?: Touch[]
255
[key: string]: any
256
}
257
258
// Touch information
259
interface Touch {
260
identifier: number
261
pageX: number
262
pageY: number
263
clientX: number
264
clientY: number
265
}
266
```
267
268
### Taro Event Types
269
270
```typescript { .api }
271
// Taro event interface
272
interface TaroEvent extends Event {
273
type: string
274
bubbles: boolean
275
cancelable: boolean
276
timeStamp: number
277
278
// Targets
279
target: TaroElement
280
currentTarget: TaroElement
281
282
// Mini-program integration
283
mpEvent?: MpEvent
284
285
// Control methods
286
stopPropagation(): void
287
stopImmediatePropagation(): void
288
preventDefault(): void
289
290
// State
291
defaultPrevented: boolean
292
eventPhase: number
293
}
294
295
// Event construction options
296
interface EventOptions {
297
bubbles?: boolean
298
cancelable?: boolean
299
detail?: any
300
}
301
```
302
303
#### Usage Examples
304
305
```typescript
306
// Event handler with full typing
307
function handleUserInteraction(event: TaroEvent): void {
308
// Access event properties with type safety
309
console.log('Event type:', event.type)
310
console.log('Target element:', event.target.tagName)
311
console.log('Bubbles:', event.bubbles)
312
313
// Access mini-program specific data
314
if (event.mpEvent) {
315
console.log('Touch data:', event.mpEvent.touches)
316
console.log('Dataset:', event.mpEvent.target.dataset)
317
}
318
319
// Control event flow
320
if (shouldStopPropagation(event)) {
321
event.stopPropagation()
322
}
323
324
if (shouldPreventDefault(event)) {
325
event.preventDefault()
326
}
327
}
328
329
// Custom event creation
330
function createCustomEvent(type: string, options: EventOptions): TaroEvent {
331
return createEvent({
332
type,
333
bubbles: options.bubbles || false,
334
cancelable: options.cancelable || false,
335
detail: options.detail
336
})
337
}
338
339
// Event listener with type safety
340
element.addEventListener('tap', (event: TaroEvent) => {
341
// TypeScript ensures event is properly typed
342
handleUserInteraction(event)
343
})
344
```
345
346
## DOM Type Definitions
347
348
### Node Type Definitions
349
350
```typescript { .api }
351
// Node type constants
352
const enum NodeType {
353
ELEMENT_NODE = 1,
354
TEXT_NODE = 3,
355
COMMENT_NODE = 8,
356
DOCUMENT_NODE = 9,
357
DOCUMENT_FRAGMENT_NODE = 11
358
}
359
360
// Base event target
361
interface TaroEventTarget {
362
addEventListener(type: string, listener: EventListener, options?: AddEventListenerOptions): void
363
removeEventListener(type: string, listener: EventListener): void
364
dispatchEvent(event: TaroEvent): boolean
365
}
366
367
// Base node interface
368
interface TaroNodeInterface extends TaroEventTarget {
369
// Identity
370
uid: string
371
sid: string
372
nodeType: NodeType
373
nodeName: string
374
375
// Tree structure
376
parentNode: TaroNode | null
377
childNodes: TaroNode[]
378
nextSibling: TaroNode | null
379
previousSibling: TaroNode | null
380
firstChild: TaroNode | null
381
lastChild: TaroNode | null
382
383
// Tree manipulation
384
appendChild(child: TaroNode): TaroNode
385
insertBefore(newChild: TaroNode, referenceChild: TaroNode | null): TaroNode
386
removeChild(child: TaroNode): TaroNode
387
replaceChild(newChild: TaroNode, oldChild: TaroNode): TaroNode
388
389
// Utilities
390
hasChildNodes(): boolean
391
}
392
```
393
394
### Element Type Definitions
395
396
```typescript { .api }
397
// Element interface
398
interface TaroElementInterface extends TaroNodeInterface {
399
// Element properties
400
tagName: string
401
id: string
402
className: string
403
404
// Content
405
innerHTML: string
406
textContent: string
407
408
// Attributes
409
attributes: Record<string, string>
410
dataset: Record<string, string>
411
412
// Style and classes
413
style: StyleInterface
414
classList: ClassListInterface
415
416
// Collections
417
children: TaroElement[]
418
419
// Attribute methods
420
getAttribute(name: string): string | null
421
setAttribute(name: string, value: string | number | boolean): void
422
removeAttribute(name: string): void
423
hasAttribute(name: string): boolean
424
425
// Selection methods
426
getElementById(id: string): TaroElement | null
427
getElementsByTagName(tagName: string): TaroElement[]
428
getElementsByClassName(className: string): TaroElement[]
429
430
// Focus
431
focus(): void
432
blur(): void
433
}
434
435
// Style interface
436
interface StyleInterface {
437
cssText: string
438
setProperty(property: string, value: string | null, priority?: string): void
439
getPropertyValue(property: string): string
440
removeProperty(property: string): void
441
[property: string]: string | Function
442
}
443
444
// ClassList interface
445
interface ClassListInterface {
446
length: number
447
add(...classNames: string[]): void
448
remove(...classNames: string[]): void
449
toggle(className: string, force?: boolean): boolean
450
contains(className: string): boolean
451
item(index: number): string | null
452
toString(): string
453
[index: number]: string
454
}
455
```
456
457
#### Usage Examples
458
459
```typescript
460
// Type-safe element manipulation
461
function setupElement(element: TaroElement): void {
462
// Properties with type safety
463
element.id = 'unique-id'
464
element.className = 'container active'
465
element.textContent = 'Hello World'
466
467
// Attributes
468
element.setAttribute('data-test', 'value')
469
element.setAttribute('aria-label', 'Button')
470
471
// Style manipulation
472
element.style.setProperty('background-color', '#ffffff')
473
element.style.color = 'black'
474
475
// Class manipulation
476
element.classList.add('visible')
477
element.classList.toggle('highlighted')
478
479
// Tree operations
480
const child = document.createElement('span')
481
element.appendChild(child)
482
}
483
484
// Custom element type
485
interface CustomElementInterface extends TaroElementInterface {
486
customProperty: string
487
customMethod(): void
488
}
489
490
class CustomElement implements CustomElementInterface {
491
// Implement all TaroElementInterface methods
492
customProperty = 'custom value'
493
494
customMethod() {
495
console.log('Custom method called')
496
}
497
498
// ... implement other required methods
499
}
500
```
501
502
## Update Type Definitions
503
504
### Update Payload Types
505
506
```typescript { .api }
507
// DOM update payload
508
interface UpdatePayload {
509
path: string // Dot-notation path (e.g., "root.cn.[0].v")
510
value: any // New value for the path
511
type?: 'set' | 'splice' | 'remove'
512
}
513
514
// Update batch
515
interface UpdateBatch {
516
payloads: UpdatePayload[]
517
callback?: () => void
518
}
519
520
// Mini-program data structure
521
interface MiniData {
522
[key: string]: any
523
524
// Common properties
525
cn?: MiniData[] // Child nodes
526
v?: string // Text value
527
st?: StyleData // Style data
528
cl?: string // Class list
529
id?: string // Element ID
530
}
531
532
// Style data for mini-programs
533
interface StyleData {
534
[property: string]: string | number
535
}
536
537
// Hydrated component data
538
interface HydratedData extends MiniData {
539
// Additional hydration metadata
540
_hydrated?: boolean
541
_path?: string
542
_uid?: string
543
}
544
```
545
546
#### Usage Examples
547
548
```typescript
549
// Create update payload
550
function createUpdatePayload(element: TaroElement, property: string, value: any): UpdatePayload {
551
return {
552
path: `${element._path}.${property}`,
553
value,
554
type: 'set'
555
}
556
}
557
558
// Batch updates
559
function batchUpdates(updates: UpdatePayload[]): UpdateBatch {
560
return {
561
payloads: updates,
562
callback: () => {
563
console.log('Batch update completed')
564
}
565
}
566
}
567
568
// Process mini-program data
569
function processMiniData(data: MiniData): void {
570
if (data.cn) {
571
data.cn.forEach(child => processMiniData(child))
572
}
573
574
if (data.v) {
575
console.log('Text content:', data.v)
576
}
577
578
if (data.st) {
579
console.log('Styles:', data.st)
580
}
581
}
582
583
// Hydration result handling
584
function handleHydratedData(hydrated: HydratedData): void {
585
if (hydrated._hydrated) {
586
console.log('Data is hydrated')
587
console.log('Path:', hydrated._path)
588
console.log('UID:', hydrated._uid)
589
}
590
}
591
```
592
593
## Configuration Type Definitions
594
595
### Page Configuration Types
596
597
```typescript { .api }
598
// Page configuration options
599
interface PageConfig {
600
// Navigation bar
601
navigationBarTitleText?: string
602
navigationBarBackgroundColor?: string
603
navigationBarTextStyle?: 'black' | 'white'
604
605
// Background
606
backgroundColor?: string
607
backgroundTextStyle?: 'dark' | 'light'
608
backgroundColorTop?: string
609
backgroundColorBottom?: string
610
611
// Pull refresh
612
enablePullDownRefresh?: boolean
613
onReachBottomDistance?: number
614
615
// Custom navigation
616
navigationStyle?: 'default' | 'custom'
617
618
// Platform specific
619
[key: string]: any
620
}
621
622
// Component configuration
623
interface ComponentConfig {
624
// Component options
625
options?: {
626
multipleSlots?: boolean
627
addGlobalClass?: boolean
628
virtualHost?: boolean
629
styleIsolation?: 'isolated' | 'apply-shared' | 'shared'
630
}
631
632
// External classes
633
externalClasses?: string[]
634
635
// Relations
636
relations?: Record<string, RelationConfig>
637
638
// Observers
639
observers?: Record<string, ObserverFunction>
640
641
// Lifecycle
642
lifetimes?: {
643
created?(): void
644
attached?(): void
645
ready?(): void
646
moved?(): void
647
detached?(): void
648
}
649
650
// Page lifecycle (for components in pages)
651
pageLifetimes?: {
652
show?(): void
653
hide?(): void
654
resize?(size: { windowWidth: number, windowHeight: number }): void
655
}
656
657
// Data and methods
658
data?: Record<string, any>
659
methods?: Record<string, Function>
660
}
661
662
// Component relation configuration
663
interface RelationConfig {
664
type: 'parent' | 'child' | 'ancestor' | 'descendant'
665
target?: string
666
linked?(target: any): void
667
linkChanged?(target: any): void
668
unlinked?(target: any): void
669
}
670
671
// Observer function type
672
type ObserverFunction = (newVal: any, oldVal: any, changedPath: string) => void
673
```
674
675
#### Usage Examples
676
677
```typescript
678
// Page configuration
679
const homePageConfig: PageConfig = {
680
navigationBarTitleText: 'Home Page',
681
navigationBarBackgroundColor: '#ffffff',
682
navigationBarTextStyle: 'black',
683
backgroundColor: '#f5f5f5',
684
enablePullDownRefresh: true,
685
onReachBottomDistance: 50
686
}
687
688
// Component configuration
689
const listComponentConfig: ComponentConfig = {
690
options: {
691
multipleSlots: true,
692
addGlobalClass: true,
693
styleIsolation: 'isolated'
694
},
695
696
externalClasses: ['custom-item-class'],
697
698
relations: {
699
'./list-item': {
700
type: 'child',
701
linked(target) {
702
console.log('List item linked:', target)
703
},
704
unlinked(target) {
705
console.log('List item unlinked:', target)
706
}
707
}
708
},
709
710
observers: {
711
'items.**': function(newVal, oldVal, changedPath) {
712
console.log('Items changed:', changedPath, newVal)
713
}
714
},
715
716
lifetimes: {
717
attached() {
718
console.log('Component attached')
719
},
720
detached() {
721
console.log('Component detached')
722
}
723
},
724
725
pageLifetimes: {
726
show() {
727
console.log('Page containing component shown')
728
}
729
},
730
731
data: {
732
items: [],
733
loading: false
734
},
735
736
methods: {
737
addItem(item: any) {
738
this.setData({
739
items: [...this.data.items, item]
740
})
741
}
742
}
743
}
744
```
745
746
## Platform Type Definitions
747
748
### Environment Types
749
750
```typescript { .api }
751
// Environment interface
752
interface Env {
753
window: Window | Record<string, never>
754
document: Document | Record<string, never>
755
}
756
757
// Current runtime state
758
interface Current {
759
app: AppInstance | null
760
router: Router | null
761
page: PageInstance | null
762
preloadData?: any
763
}
764
765
// Router state
766
interface Router {
767
params: Record<string, unknown>
768
path: string
769
$taroPath: string
770
onReady: string
771
onHide: string
772
onShow: string
773
exitState?: any
774
}
775
```
776
777
### Function Types
778
779
```typescript { .api }
780
// Generic function type
781
type TFunc = (...args: any[]) => any
782
783
// Event listener type
784
type EventListener = (event: TaroEvent) => void | boolean
785
786
// Timer handler type
787
type TimerHandler = string | Function
788
789
// Frame request callback
790
type FrameRequestCallback = (timestamp: number) => void
791
792
// Mutation callback
793
type MutationCallback = (mutations: MutationRecord[], observer: MutationObserver) => void
794
```
795
796
### Utility Types
797
798
```typescript { .api }
799
// Options interface
800
interface Options {
801
prerender: boolean
802
debug: boolean
803
}
804
805
// Cache interface
806
interface CacheInterface<T = any> {
807
set(key: string, value: T): void
808
get(key: string): T | undefined
809
has(key: string): boolean
810
delete(key: string): boolean
811
clear(): void
812
size: number
813
}
814
815
// Performance interface
816
interface PerformanceInterface {
817
start(id: string): void
818
stop(id: string, now?: number): void
819
delayStop(id: string, delay?: number): void
820
}
821
```
822
823
#### Usage Examples
824
825
```typescript
826
// Type-safe utility usage
827
function createUtilityFunction(): TFunc {
828
return (...args: any[]) => {
829
console.log('Arguments:', args)
830
return args[0]
831
}
832
}
833
834
// Event handling with proper types
835
function setupEventHandling(element: TaroElement): void {
836
const handler: EventListener = (event: TaroEvent) => {
837
console.log('Event handled:', event.type)
838
return false // Prevent further handling
839
}
840
841
element.addEventListener('tap', handler)
842
}
843
844
// Performance monitoring with types
845
function monitorPerformance(perf: PerformanceInterface): void {
846
perf.start('operation')
847
// ... perform operation
848
perf.stop('operation')
849
}
850
851
// Cache usage with types
852
function setupCache(): CacheInterface<string> {
853
const cache = new RuntimeCache<string>()
854
855
cache.set('key1', 'value1')
856
const value = cache.get('key1') // TypeScript knows this is string | undefined
857
858
return cache
859
}
860
```
861
862
## Advanced Type Patterns
863
864
### Generic Constraints
865
866
```typescript { .api }
867
// Component with data constraints
868
interface ComponentWithData<T extends Record<string, any> = Record<string, any>> extends Component<T> {
869
data: T
870
setData(updates: Partial<T>): void
871
}
872
873
// Page with props constraints
874
interface PageWithProps<P extends PageProps = PageProps> extends ReactPageInstance<P> {
875
props: P
876
}
877
878
// Event handler with payload constraints
879
interface EventHandlerWithPayload<T = any> {
880
(event: TaroEvent & { detail: T }): void
881
}
882
```
883
884
### Conditional Types
885
886
```typescript { .api }
887
// Platform-specific types
888
type PlatformSpecific<T, P extends 'web' | 'miniprogram'> =
889
P extends 'web' ? T & WebSpecific : T & MiniprogramSpecific
890
891
interface WebSpecific {
892
webOnlyProperty: string
893
}
894
895
interface MiniprogramSpecific {
896
mpOnlyProperty: string
897
}
898
899
// Optional lifecycle based on platform
900
type ConditionalLifecycle<P extends 'web' | 'miniprogram'> =
901
P extends 'web' ? WebLifecycle : MiniprogramLifecycle
902
903
interface WebLifecycle {
904
componentDidMount?(): void
905
componentWillUnmount?(): void
906
}
907
908
interface MiniprogramLifecycle {
909
onLoad?(): void
910
onUnload?(): void
911
}
912
```
913
914
#### Usage Examples
915
916
```typescript
917
// Generic component with constraints
918
class TypedComponent<T extends Record<string, any>> implements ComponentWithData<T> {
919
data: T
920
921
constructor(initialData: T) {
922
this.data = initialData
923
}
924
925
setData(updates: Partial<T>): void {
926
this.data = { ...this.data, ...updates }
927
}
928
}
929
930
// Usage
931
interface MyComponentData {
932
count: number
933
message: string
934
}
935
936
const component = new TypedComponent<MyComponentData>({
937
count: 0,
938
message: 'Hello'
939
})
940
941
component.setData({ count: 1 }) // Type-safe updates
942
943
// Platform-specific implementation
944
function createPlatformComponent<P extends 'web' | 'miniprogram'>(
945
platform: P
946
): PlatformSpecific<Component, P> {
947
// Implementation varies by platform
948
if (platform === 'web') {
949
return {
950
webOnlyProperty: 'web-specific'
951
} as any
952
} else {
953
return {
954
mpOnlyProperty: 'miniprogram-specific'
955
} as any
956
}
957
}
958
```
959
960
## Runtime Constants
961
962
### System Constants
963
964
```typescript { .api }
965
import {
966
PROPERTY_THRESHOLD,
967
TARO_RUNTIME,
968
HOOKS_APP_ID,
969
SET_DATA,
970
PAGE_INIT,
971
ROOT_STR,
972
HTML,
973
HEAD,
974
BODY,
975
APP,
976
CONTAINER,
977
DOCUMENT_ELEMENT_NAME,
978
DOCUMENT_FRAGMENT,
979
ID,
980
UID,
981
CLASS,
982
STYLE,
983
FOCUS,
984
VIEW,
985
STATIC_VIEW,
986
PURE_VIEW,
987
CLICK_VIEW,
988
PROPS,
989
DATASET,
990
OBJECT,
991
VALUE,
992
INPUT,
993
CHANGE,
994
CUSTOM_WRAPPER,
995
TARGET,
996
CURRENT_TARGET,
997
TYPE,
998
CONFIRM,
999
TIME_STAMP,
1000
KEY_CODE,
1001
TOUCHMOVE,
1002
DATE,
1003
SET_TIMEOUT,
1004
COMPILE_MODE,
1005
CATCHMOVE,
1006
CATCH_VIEW,
1007
COMMENT,
1008
ON_LOAD,
1009
ON_READY,
1010
ON_SHOW,
1011
ON_HIDE,
1012
OPTIONS,
1013
EXTERNAL_CLASSES,
1014
EVENT_CALLBACK_RESULT,
1015
BEHAVIORS,
1016
A,
1017
CONTEXT_ACTIONS
1018
} from '@tarojs/runtime'
1019
1020
// Core system constants
1021
const PROPERTY_THRESHOLD: 2046 // Max property count for setData
1022
const TARO_RUNTIME: 'Taro runtime'
1023
const HOOKS_APP_ID: 'taro-app'
1024
1025
// Page context actions
1026
enum CONTEXT_ACTIONS {
1027
INIT = '0', // Initialize new page
1028
RESTORE = '1', // Restore cached page
1029
RECOVER = '2', // Recover from cache
1030
DESTORY = '3' // Clean up page context
1031
}
1032
1033
// DOM node names
1034
const ROOT_STR: 'root'
1035
const HTML: 'html'
1036
const HEAD: 'head'
1037
const BODY: 'body'
1038
const APP: 'app'
1039
const CONTAINER: 'container'
1040
const DOCUMENT_ELEMENT_NAME: '#document'
1041
const DOCUMENT_FRAGMENT: 'document-fragment'
1042
const COMMENT: 'comment'
1043
1044
// Element types
1045
const VIEW: 'view'
1046
const STATIC_VIEW: 'static-view'
1047
const PURE_VIEW: 'pure-view'
1048
const CLICK_VIEW: 'click-view'
1049
const CATCH_VIEW: 'catch-view'
1050
const CUSTOM_WRAPPER: 'custom-wrapper'
1051
1052
// Attribute names
1053
const ID: 'id'
1054
const UID: 'uid'
1055
const CLASS: 'class'
1056
const STYLE: 'style'
1057
const PROPS: 'props'
1058
const DATASET: 'dataset'
1059
const VALUE: 'value'
1060
1061
// Event types
1062
const INPUT: 'input'
1063
const CHANGE: 'change'
1064
const FOCUS: 'focus'
1065
const TOUCHMOVE: 'touchmove'
1066
const TARGET: 'target'
1067
const CURRENT_TARGET: 'currentTarget'
1068
const TYPE: 'type'
1069
const CONFIRM: 'confirm'
1070
const TIME_STAMP: 'timeStamp'
1071
const KEY_CODE: 'keyCode'
1072
const EVENT_CALLBACK_RESULT: 'e_result'
1073
1074
// Lifecycle events
1075
const ON_LOAD: 'onLoad'
1076
const ON_READY: 'onReady'
1077
const ON_SHOW: 'onShow'
1078
const ON_HIDE: 'onHide'
1079
1080
// Mini-program specific
1081
const COMPILE_MODE: 'compileMode'
1082
const CATCHMOVE: 'catchMove'
1083
const OPTIONS: 'options'
1084
const EXTERNAL_CLASSES: 'externalClasses'
1085
const BEHAVIORS: 'behaviors'
1086
1087
// Other constants
1088
const OBJECT: 'object'
1089
const DATE: 'Date'
1090
const SET_TIMEOUT: 'setTimeout'
1091
const A: 'a'
1092
```
1093
1094
#### Usage Examples
1095
1096
```typescript
1097
// Use constants for consistent string values
1098
function createTaroElement(tagName: string = VIEW): TaroElement {
1099
const element = new TaroElement()
1100
element.tagName = tagName
1101
return element
1102
}
1103
1104
// Page context management
1105
function handleContextAction(action: CONTEXT_ACTIONS): void {
1106
switch (action) {
1107
case CONTEXT_ACTIONS.INIT:
1108
initializePage()
1109
break
1110
case CONTEXT_ACTIONS.RESTORE:
1111
restorePage()
1112
break
1113
case CONTEXT_ACTIONS.RECOVER:
1114
recoverPage()
1115
break
1116
case CONTEXT_ACTIONS.DESTORY:
1117
cleanupPage()
1118
break
1119
}
1120
}
1121
1122
// Property threshold checking
1123
function safeSetData(data: Record<string, any>): void {
1124
const propertyCount = Object.keys(data).length
1125
1126
if (propertyCount > PROPERTY_THRESHOLD) {
1127
console.warn(`Property count ${propertyCount} exceeds threshold ${PROPERTY_THRESHOLD}`)
1128
// Batch the updates or use alternative approach
1129
} else {
1130
// Safe to set data
1131
this.setData(data)
1132
}
1133
}
1134
1135
// Event type checking
1136
function isUserInputEvent(event: TaroEvent): boolean {
1137
return event.type === INPUT || event.type === CHANGE
1138
}
1139
1140
// DOM tree checking
1141
function isRootElement(element: TaroElement): boolean {
1142
return element.nodeName === ROOT_STR || element.nodeName === HTML
1143
}
1144
```
1145
1146
The comprehensive type system ensures type safety across all aspects of Taro runtime development, providing clear contracts for components, events, DOM operations, and platform integrations while maintaining flexibility for custom implementations and platform-specific optimizations.