我可以限制属性装饰器只能应用于TypeScript中的有限类型吗?

我可以限制属性装饰器只能应用于TypeScript中的有限类型吗?,typescript,Typescript,我想使装饰器只对字符串属性起作用,如果不起作用,则生成错误。可能吗 function deco () { // How can I make the restrictions here? return function (target:any, key:string) { } } class A { @deco() // This should be valid foo:string @deco() // This should be invalid bar:nu

我想使装饰器只对字符串属性起作用,如果不起作用,则生成错误。可能吗

function deco () {
  // How can I make the restrictions here?
  return function (target:any, key:string) {
  }
}

class A {
  @deco() // This should be valid
  foo:string

  @deco() // This should be invalid
  bar:number
}
允许的类型=
T[K]扩展允许//如果T扩展允许
? T/'返回'T
:从不;//否则“回归”永远不会
函数deco(){
返回函数<
T、 //推断目标的类型
K扩展keyof T//推断目标键的类型
>(
target:Allowed,//仅当T[K]为字符串时才允许
关键字:K
) { }
}
甲级{
@deco()//这应该是有效的
foo!:字符串
@deco()//这应该是无效的
酒吧!:号码
}

非常有魅力!
type Allowed<T, K extends keyof T, Allow> =
    T[K] extends Allow // If T extends Allow
        ? T            // 'return' T
        : never;       // else 'return' never

function deco () {
    return function <
        T, // infers typeof target    
        K extends keyof T // infers typeof target's key
    >(
        target: Allowed<T, K, string>, // only allow when T[K] is string 
        key: K
    ) { }
}

class A {
  @deco() // This should be valid
  foo!: string

  @deco() // This should be invalid
  bar!: number
}