Why interface with optional property is treated differently from interface without? Are all the properties considered optional for type assertion if none of them defined optional explicitly?
interface WithOptionalProperty {
requiredProperty: string;
optionalProperty?: string;
}
//compilation error 'requiredProperty' is missing
let a = { optionalProperty: '' } as WithOptionalProperty;
interface WithoutOptionalProperties {
requiredProperty: string;
anotherRequiredProperty: string;
}
//but this works as expected
let b = { anotherRequiredProperty: '' } as WithoutOptionalProperties;
This is because type assertions between types A and B succeed if A is assignable to B or B is assignable to A (simplified explanation).
Neither of these conditions are true in your case 1. But one of these is true in case B (hence the assertion compiles fine).
https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html
Double Assertion : https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html#double-assertion
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