【问题标题】:Typing for optional callable decorator in Typescript在 Typescript 中键入可选的可调用装饰器
【发布时间】:2017-09-02 23:05:00
【问题描述】:

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

@model
class User {}

@model()
class User {}

@model('User')
class User {}

我尝试使用来自lib.es6.d.tsClassDecorator,但没有成功:

// 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 类型呢?

【问题讨论】:

    标签: javascript typescript decorator typescript-typings


    【解决方案1】:

    问题是你使用的是联合类型,这些类型的变量只有两种类型的共同成员,所以在这种情况下,由于只有一种类型是可调用的,联合将不可调用

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

    export const model: ClassDecorator & CallableModelDecorator;
    

    【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2017-03-07
    • 2021-07-15
    • 1970-01-01
    • 2020-06-09
    • 2018-06-08
    • 2019-11-18
    • 2021-10-14
    • 2015-02-22
    相关资源
    最近更新 更多