Reputation: 2202
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
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
}
Upvotes: 1