簡體   English   中英

泛型方法裝飾器鍵入

[英]Generic method decorator typing

我試圖使foo通用裝飾器符合MethodDecorator類型:

const foo: MethodDecorator = function <T extends Function = Function>(
    target: object,
    propertyKey: string | symbol,
    descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> {
    return {
        configurable: true,
        enumerable: false,
        value: descriptor.value!.bind(null)
    };
}

foo可以直接用作輔助函數,我希望有一個選項可以另外將其鍵入為泛型。

這是錯誤:

Type '<T extends Function = Function>(target: object, propertyKey: string | symbol, descriptor: TypedPr...' is not assignable to type 'MethodDecorator'.
  Types of parameters 'descriptor' and 'descriptor' are incompatible.
    Type 'TypedPropertyDescriptor<T>' is not assignable to type 'TypedPropertyDescriptor<Function>'.
      Types of property 'value' are incompatible.
        Type 'T | undefined' is not assignable to type 'Function | undefined'.
          Type 'T' is not assignable to type 'Function | undefined'.
            Type 'T' is not assignable to type 'Function'.

foo如何符合MethodDecorator

似乎MethodDecorator不是通用類型別名 ,因此無法縮小T類型。

type Foo<T> = (x: T) => T; // this one is generic
type Bar = (x: T) => T; // and this is not

這是有道理的,因為在foo中所做的假設(即, descriptor.value具有bind屬性)對於MethodDecorator通常來說是不正確的。

由於type僅僅是別名,我們可以定義自己的別名。

type TypedMethodDecorator = <T extends Function>(
    target: Object,
    propertyKey: string | symbol,
    descriptor: TypedPropertyDescriptor<T>
) => TypedPropertyDescriptor<T> | void;

const foo: TypedMethodDecorator = function (target, propertyKey, descriptor) {
    return {
        configurable: true,
        enumerable: false,
        value: descriptor.value!.bind(null)
    };
}

class C {
    @foo
    m() {
        console.log('this:', this);
    }
}

new C().m(); // 'this: null'

由於類型推斷,編譯器認為foo是有效的裝飾器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM