繁体   English   中英

在Typescript中键入可选的可调用装饰器

[英]Typing for optional callable decorator in Typescript

我正在为某些js库编写打字稿类型。 我需要声明可选的可调用装饰器:

@model
class User {}

@model()
class User {}

@model('User')
class User {}

我试图使用ClassDecoratorlib.es6.d.ts但是没有运气:

// works
export const model: ClassDecorator;

// error TS1238: Unable to resolve signature of class decorator when called as an expression. Cannot invoke an expression whose type lacks a call signature. Type 'ClassDecorator | CallableModelDecorator' has no compatible call signatures
type CallableModelDecorator = (name?: string) => ClassDecorator;
export const model: ClassDecorator | CallableModelDecorator;

当然,我可以手动输入作为解决方法:

export function model<TFunction extends Function>(target: TFunction): TFunction | void;
export function model(name?: string):
  <TFunction extends Function>(target: TFunction) => TFunction | void;

但是在这种情况下,如何重用现有的ClassDecorator类型?

问题是您正在使用联合类型,这些类型的变量仅具有两种类型的公共成员,因此在这种情况下,由于只有一种类型是可调用的,因此联合将不可调用

您正在寻找一个交集类型,该交集将具有两种类型的成员

export const model: ClassDecorator & CallableModelDecorator;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM