What I have
I have a method in a class which I want to accept any object as an argument but I don't want to use any, for this I use a generic and extend object.
class MyClass {
saveObject<T extends object>(object: T | null) {}
}
With this implementation, @typescript-eslint/ban-types rule complains with the following error:
Don't use 'object' as a type. The 'object' type is currently hard to use see this issue(https://github.com/microsoft/TypeScript/issues/21732)). Consider using 'Record<string, unknown>' instead, as it allows you to more easily inspect and use the keys. ok, then I will listen to Eslint and do the following implementation:
class MyClass {
saveObject<T extends Record<string, unknown>>(object: T | null) {}
}
with the above implementation, the Eslint error disappears, so I try to execute the method with a random object:
anyOtherMethodInMyCode(payment: IPaymentModel | null): void {
// execute our method
this.saveObject(payment);
}
But the typescript compiler throws a new error:
TS2345: Argument of type 'IPaymentModel | null' is not assignable to parameter of type 'Record<string, unknown> | null'.
Type 'IPaymentModel' is not assignable to type 'Record<string, unknown>'.
Index signature is missing in type 'IPaymentModel'.
One option is to use Type Assertion in the argument passed to the method as follow:
anyOtherMethodInMyCode(payment: IPaymentModel | null): void {
// execute our method with Type Assertion
this.saveObject(payment as Record<string, unknown>);
}
With the above, TS compiler errors disappear but it is not optimal to have to do this(Type Assertion) in all places where the method is executed.
What I want
I don't understand how to accept any object as an argument without having this kind of errors without the need to use any.