Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript type assertions - interface with optional members

Tags:

typescript

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;
like image 383
Aleksey L. Avatar asked Sep 21 '26 09:09

Aleksey L.


1 Answers

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).

More

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

like image 125
basarat Avatar answered Sep 23 '26 06:09

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!