Given the following interface:
interface Request
{
name: string;
email: string;
}
I would have thought that the following lines of code were functionally identical at design time:
var request1: Request = {name: "John"};
var request2 = {name: "John"} as Request;
But they are not. The second line compiles, whereas the first complains that the email property is missing.
If Typescript believes that all non-optional properties of the type must be specified, why doesn't it complain about type assertion using the as Request on an object that's missing a property.
And is there a casting syntax that would enforce this stronger typing? (The <Request>(...) syntax doesn't do so either.)
The purpose of a type assertion (either the as Request syntax of the <Request> syntax) is to tell typescript "i know better than you, so don't check my work here". For that reason, type checking is more or less turned off. It still does a very loose form of typechecking to rule out the more egregious cases, but that won't catch the case you have. (And if it does find something you can turn it completely off by doing as unknown as Request).
And is there a casting syntax that would enforce this stronger typing?
If you want a strict type, then you use the colon syntax that you had on your first line.
var request1: Request = {name: "John"};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With