简体   繁体   English

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

[英]Typing for optional callable decorator in Typescript

I am writing typescript typings for some js library. 我正在为某些js库编写打字稿类型。 I need to declare optionally callable decorator: 我需要声明可选的可调用装饰器:

@model
class User {}

@model()
class User {}

@model('User')
class User {}

I tried to use ClassDecorator from lib.es6.d.ts but with no luck: 我试图使用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;

Of course I can make manual typing as workaround: 当然,我可以手动输入作为解决方法:

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

But how can I reuse existing ClassDecorator type in this case? 但是在这种情况下,如何重用现有的ClassDecorator类型?

The problem is you are using an union type, variables of these types only have the common members of both types, so in this case since only one of the types is callable, the union will not be callable 问题是您正在使用联合类型,这些类型的变量仅具有两种类型的公共成员,因此在这种情况下,由于只有一种类型是可调用的,因此联合将不可调用

You are looking for an intersection type, that will have member of both of type types 您正在寻找一个交集类型,该交集将具有两种类型的成员

export const model: ClassDecorator & CallableModelDecorator;

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

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