In TypeScript, I can do this:
function someFunction(options:any) {
// Do something
}
interface MyOptions {
userId: number;
verbose: boolean;
}
const options: MyOptions = {
userId: 12345,
doesntExist: false, // Error
}
someFunction(options);
And that will give me a compilation error on the "doesntExist" property.
The problem is when I do the same thing without creating an intermediate variable:
someFunction({
userId: 12345,
doesntExist: false, // no error
});
In that case, since someFunction
accepts any
as a parameter, type checking is not enforced. Even if I do this, the compiler doesn't complain:
someFunction({
userId: 12345,
doesntExist: false, // no error
} as MyOptions);
So I'm wondering is there any way to enforce type checking without creating the intermediate variable?
What I was wondering is if there's a syntax that allows me to say "while the function takes 'any' as parameter, I declare that the object I'm passing is of type T"
What you are describing is generics.
function someFunction<T>(options: T) {
// Do something
}
If you just call the function without specifying the generic T
then you won't get an error because typescript will assume that T
is the type for whatever argument you provided.
But you can manually enter the generic as MyOptions
and you will get an error when your argument isn't right.
someFunction<MyOptions>({
userId: 12345,
doesntExist: false // error
})
Here we get the error Argument of type '{ userId: number; doesntExist: boolean; }' is not assignable to parameter of type 'MyOptions'. Object literal may only specify known properties, and 'doesntExist' does not exist in type 'MyOptions'.