I want to be able to pass interface into a certain function in typescript, where that function can accept any object type, so long as all of its properties are of a certain type.
Consider the following example:
function DoSomething(args: { readonly [propertyName: string]: string }) {
// do something
}
// MyArgs is really just a more strongly typed version of {[propertyName: string]: string}
interface MyArgs {
foo: string;
bar: string;
}
var someArgs: MyArgs = {
foo: "foo",
bar: "bar"
}
DoSomething({ foo: "foo", bar: "bar" }); // works
DoSomething(someArgs); // compile error: Index signature is missing in type 'MyArgs'
This doesn't work because someArgs can not be cast to the parameter type used for the function's argument.
This is different from Typescript: Index signature is missing in type because of the readonly modifier which means that the DoSomething function cannot add new propertly to args. This means that an instance of MyArgs will still comply with this interface signature after DoSomething has been invoked against it.
How can I represent this in Typescript? Is there another way of doing this that I am missing?
readonlymodifier which means that theDoSomethingfunction cannot add new propertly toargs, which means that an instance ofMyArgswill still comply with this signature afterDoSomethinghas been invoked against it.readonlydoes typescript compile it? I don't think readonly or not does not make any difference here at all.