[英]Typing for optional callable decorator in Typescript
我正在為某些js庫編寫打字稿類型。 我需要聲明可選的可調用裝飾器:
@model
class User {}
@model()
class User {}
@model('User')
class User {}
我試圖使用ClassDecorator
的lib.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.