My goal is to iterate over specific keys of a class without using the index signature [key:string]:any
as it is not the recommended approach.
This is my proposed solution:
interface I {
a: string,
b: number
}
type NullKeysOf<T> = {
[P in keyof T]: null
}
type PartialNullKeysOf<T> = Partial<NullKeysOf<T>>;
const obj:PartialNullKeysOf<I> = {
a:null
}
class A<M extends I> implements I{
a:string;
b:number;
obj:PartialNullKeysOf<M>
constructor(a:string, b:number, obj:PartialNullKeysOf<M>){
this.a = a;
this.b = b;
this.obj = obj;
}
public loop(){
for(const k in this.obj){
console.log(this[k]);
}
}
}
const a = new A<I>('',3,obj);
a.loop();
Check out the TypeScript Playground here
I encountered an error message:
Type 'Extract<keyof M, string>' cannot be used to index type 'this'.
I am puzzled by why the type of k
in the loop is Extract<keyof M, string>
.
Shouldn't it be typeof I
instead?