在`tc 39/proposal-decorators`中定义的`ClassDecorator`类型在没有TypeScript错误的情况下不适用

5kgi1eie  于 2023-04-07  发布在  TypeScript
关注(0)|答案(1)|浏览(146)

我得到了错误
TS 1270:装饰器函数返回类型“void|函数“”不可赋值给类型“void|typeof ReactiveStateExperimentalSample'.
类型“Function”不可分配给类型“void|typeof ReactiveStateExperimentalSample'.
类型“Function”不能分配给类型“typeof ReactiveStateExperimentalSample”。 类型“Function”未提供签名“new()”的匹配项:ReactiveStateExperimentalSample’。
当试图应用装饰器时

const VueComponentOptions: (
  value: Function,
  context: {
    kind: "class";
    name: string | undefined;
    addInitializer(initializer: () => void): void;
  }
) => Function | void = (
  value: Function, context: ClassDecoratorContext
): Function | void => {

  const vueOptions: ComponentOptions = {
    methods: {},
    computed: {}
  };

  return defineComponent(vueOptions);

};

到类

@VueComponentOptions
export default class ReactiveStateExperimentalSample {

}

根据tc 39/proposal-decorators,类装饰器的签名是

type ClassDecorator = (value: Function, context: {
  kind: "class";
  name: string | undefined;
  addInitializer(initializer: () => void): void;
}) => Function | void;

TypeScript 5中没有这样的类型(更确切地说,在typescript/lib/lib.decorators.d.ts中)。typescript/lib/lib.decorators.legacy.d.ts中有这样的类型,但legacy是legacy。
是我做错了什么,还是它只是不成熟的API?TypeScript 5不再是测试版,因此“实验装饰器”不再是实验性的。

yuvru6vn

yuvru6vn1#

TS装饰器尚未完全兼容TC39

// logs [class X{}]
@((...a) => console.log(a))
class X {}

https://www.typescriptlang.org/play?experimentalDecorators=true&ts=5.1.0-dev.20230402#code/PTAEBsHsHMGdQNoGNwENbwBoG8C+BdAKAAEAKUgOitQEpQBeAPlCUgDtZJwBTCqaUrRqEU6LKDyEgA
因此,同时你的装饰应该遵循目前的打字

// lib.es5.d.ts
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;

相关问题