Type assertions

We are supposed to put type definitions on our variables in TypeScript. But I often had to resort to the frowned-upon type any. Here I declare sng but then I cannot use it for a bog standard shift. The language’s shift method can return undefined. My definition of ITEM (elsewhere) does not allow that because (duh, of course) it is a type definition. I get Type ‘ITEM | undefined’ is not assignable to type ITEM:

I would resort to this:

Yesterday I finally found a better solution. Use a type assertion on the shift:

If a Type Assertion is incorrect it can lead to runtime errors that Typescript would normally prevent. But in this case I am confident that this line of code will never return an undefined value.

sng might be null. It is immediately after it is declared in the first line. That does not matter to the type assertion because 1. the type assertion is only for its own line of code, and 2. I am promising the compiler that this shift will never return something that is undefined. I am not promising it will never return a null.

Leave a Reply

Your email address will not be published. Required fields are marked *