diff --git a/ArkUI/entry/src/main/ets/pages/ArktsTypeConversion.ets b/ArkUI/entry/src/main/ets/pages/ArktsTypeConversion.ets index fe97c5b92e88c2e39705ed4ad057f22a4a7269e8..caa093d002fb9f9a1f1de8a550bf6985040bb6dc 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