Given the following sample code
interface MyInterface { foo: string; }
function doSomethingWith(x: Record<string, unknown>) { /* ... */ }
const myInterface: MyInterface = { foo: 'bar' };
doSomethingWith(myInterface);
It is not possible to pass the variable to the function because
Argument of type 'MyInterface' is not assignable to parameter of type 'Record<string, unknown>'. Index signature for type 'string' is missing in type 'MyInterface'.(2345)
I solved the problem by converting the variable
const myInterfaceAsRecord = (myInterface as unknown) as Record<string, unknown>;
and would like to know if there are any "better" ways to pass in the interface to the function?
CodePudding user response:
Just use type
instead interface
type MyInterface = { foo: string; }
function doSomethingWith(x: Record<string, unknown>) { /* ... */ }
const myInterface: MyInterface = { foo: 'bar' };
doSomethingWith(myInterface);
See this answer for more context
CodePudding user response:
One option would be to extend the interface from the record:
interface MyInterface extends Record<string, unknown> { foo: string; }
function doSomethingWith(x: Record<string, unknown>) { /* ... */ }
const myInterface: MyInterface = { foo: 'bar' };
doSomethingWith(myInterface);