When working with TypeScript, it is possible to define a function and an interface like this:
function someFunction(options: any) {
// Do something
}
interface MyOptions {
userId: number;
verbose: boolean;
}
const options: MyOptions = {
userId: 12345,
doesntExist: false, // Error
}
someFunction(options);
If we try to assign a property that doesn't exist in the defined interface, it will result in a compilation error.
However, if we skip creating the intermediate variable and directly pass the object to the function like this:
someFunction({
userId: 12345,
doesntExist: false, // no error
});
In this scenario, because the someFunction
accepts any
as a parameter, type checking is not enforced. Even using as MyOptions
won't trigger the compiler to complain.
Therefore, the question arises - is there a way to enforce type checking without the need for creating an intermediate variable?