I am currently working on developing a generic component in Angular and Typescript version 4.4.4. The goal is to create a component where I can set both an object (obj) and specific keys (properties).
Here's a simplified version of my text component:
// text.component.ts
class TextComponent<T, K extends Extract<keyof T, string>> {
@Input()
obj : T;
@Input()
key: K;
constructor(){}
// The challenge lies in not being able to change the function signature for simulation purposes
currency(cost: string | number) {
console.log('func::currency', cost);
}
test(){
this.currency(this.obj[this.key]);
}
}
// text.component.html (template)
// Currency is a built-in PipeTransform feature in Angular
//{{ obj[key] | currency:'US' }}
Unfortunately, I have encountered an error that I'm struggling to resolve.
Argument of type 'T[K]' is not assignable to parameter of type 'string | number'.
Type 'T[Extract<keyof T, string>]' is not assignable to type 'string | number'.
Type 'T[string]' is not assignable to type 'string | number'.
Type 'T[string]' is not assignable to type 'number'.
Type 'T[Extract<keyof T, string>]' is not assignable to type 'number'.
Type 'T[K]' is not assignable to type 'number'.
Type 'T[Extract<keyof T, string>]' is not assignable to type 'number'.
Type 'T[string]' is not assignable to type 'number'.
Although using
this.currency(this.obj[this.key] as any);
might be a temporary solution, I would prefer not to go down that route.