首页 > 解决方案 > 如何帮助 Typescript 推断 PropertyDecorator 工厂函数的泛型参数?

问题描述

假设我有一个像这样的通用装饰器工厂:

declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;

// ^^^ Note: PropertyDecorator should be available as a built-in type with experimental decorators enabled.

export type Transformer<T, U> = (value: T) => U;

function PropertyTransformer<T, U>(to: Transformer<T, U>, from: Transformer<U, T>): PropertyDecorator {
  return (target, propertyKey) => {
    // Do some decorator stuff...
  }
}

是否可以将类型限制T为装饰属性恰好是(即T extends typeof target[propertyKey])的任何类型?

标签: typescripttypescript-typingstypescript-genericstypescript-types

解决方案


推荐阅读