jayatubi
jayatubi

Reputation: 2202

Can I restrict a property decorator could only be applied to limited types in TypeScript?

I want to make a decorator only works on string properties and generate error if not. Is that possible?

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
}

Upvotes: 0

Views: 27

Answers (1)

Zou Jeff
Zou Jeff

Reputation: 883

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
}

Playground Link

Upvotes: 1

Related Questions