From 4609d218655609f565bfd17d6bfe3ab435bb2179 Mon Sep 17 00:00:00 2001 From: zhangxCode Date: Wed, 4 Jun 2025 10:49:03 +0800 Subject: [PATCH] =?UTF-8?q?FAQ=EF=BC=9A=E6=96=B0=E5=A2=9E=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=90=8C=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/ets/pages/ArktsTypeConversion.ets | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/ArkUI/entry/src/main/ets/pages/ArktsTypeConversion.ets b/ArkUI/entry/src/main/ets/pages/ArktsTypeConversion.ets index fe97c5b..caa093d 100644 --- a/ArkUI/entry/src/main/ets/pages/ArktsTypeConversion.ets +++ b/ArkUI/entry/src/main/ets/pages/ArktsTypeConversion.ets @@ -2,7 +2,7 @@ * FAQ:ArkTS类型转换方法,除了使用as是否有其他方法 */ class TargetClass { - someProperty: string = ''; + someProperty?: string; someMethod: () => void = () => { }; } @@ -21,6 +21,20 @@ function testFn(anyObject: TargetClass) { const anyObject = new TargetClass(); +// [Start type_is] +function isTargetClass(obj: object) { + return obj instanceof TargetClass && obj.someProperty === 'expectedValue'; +} + +if (isTargetClass(anyObject)) { + // Now it is safe to use anyObject as an instance of Target Class +} else { + // Dealing with objects that do not conform to the Target Class +} + +// [End type_is] + + // [Start type_as] function testFn2(anyObject: TargetClass) { try { @@ -31,4 +45,20 @@ function testFn2(anyObject: TargetClass) { // Dealing with situations where type conversion fails or method calls are incorrect } } -// [End type_as] \ No newline at end of file + +// [End type_as] + +// [Start type_asserts] +function assertIsTargetClass(obj: object) { + if (!(obj instanceof TargetClass)) { + throw new Error('Object is not an instance of TargetClass'); + } +} + +try { + assertIsTargetClass(anyObject); + // Now it is safe to use anyObject as an instance of Target Class +} catch (error) { + // Failure to handle type assertion +} +// [End type_asserts] \ No newline at end of file -- Gitee