HarmonyOS鸿蒙Next中装饰器中无法使用泛型

HarmonyOS鸿蒙Next中装饰器中无法使用泛型

自定义修饰器中无法使用泛型报错:Statement expected 详见附件 关键代码片段:

```javascript
function Validate(errorMsg: string): MethodDecorator {
  return (target: Object, propertyKey: string | Symbol, descriptor: PropertyDescriptor) => {
    const originalMethod: Function = descriptor.value;
    descriptor.value = (arg: string): Error | string => {
      console.log('这里写检验逻辑');
      return originalMethod(arguments);
    };
  };
}

// 使用方法
[@Validate](/user/Validate)<string>('Name must be a non-empty string.')
load() {
  return 'd';
}

更多关于HarmonyOS鸿蒙Next中装饰器中无法使用泛型的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复
function Validate<T>(errorMsg: T): MethodDecorator {
    return (target: Object, propertyKey: string | Symbol, descriptor: PropertyDescriptor) => {
        console.log('success')
        const originalMethod: Function = descriptor.value;
        descriptor.value = (arg: string): Error | string => {
            console.log('这里写检验逻辑')
            return originalMethod(arguments)
        };
    };
}

@Validate("Name must be a non-empty string.")
load(){
    return 'd'
}

更多关于HarmonyOS鸿蒙Next中装饰器中无法使用泛型的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你要不看看你自己写的啥,你装饰器中接收泛型的东西在哪?

在HarmonyOS鸿蒙Next中,装饰器无法直接使用泛型。这是由于装饰器本身的设计限制了泛型的使用。装饰器在鸿蒙系统中主要用于扩展类、方法或属性的功能,但其实现方式并不支持泛型参数的直接传递。这意味着在装饰器定义中无法声明泛型类型,也无法在装饰器中使用泛型参数。

具体来说,鸿蒙的装饰器实现基于特定的语法和规则,这些规则限制了装饰器对泛型的支持。泛型通常在类或方法中用于增强代码的复用性和类型安全性,但在装饰器中,由于装饰器的特殊作用机制,泛型无法被直接应用。因此,在鸿蒙Next中,如果需要使用泛型,应将其放在类或方法中,而不是装饰器内。

在HarmonyOS鸿蒙Next中,装饰器确实不支持直接使用泛型。这是因为装饰器在编译时会被转换为具体的类型,而泛型在编译时并未确定具体类型,导致无法直接使用。解决方法是:在装饰器内部通过类型推断或类型断言来处理泛型类型,或者将泛型类型作为参数传递给装饰器函数。这样可以绕过直接使用泛型的限制,实现类似的功能。

回到顶部