Typescript type statements - an interface with optional members

Why is an interface with an additional property handled differently than an interface? Are all properties that are considered optional for a type statement if none of them are explicitly defined?

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;
+4
source share
1 answer

This is because type statements between types A and B are successful, if A is assigned to B or B, then A is assigned (simplified explanation).

None of these conditions is true in your case 1. But one of them is true in case B (therefore, the statement compiles fine).

More details

https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

: https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html#double-assertion

+1

Source: https://habr.com/ru/post/1649745/


All Articles