3

I had the impression that a type assertion to string would result in a previously-unknown type to turn into a string. I appreciate some explanation as to why this is not the case.

$npx ts-node
> undefined as string
[eval].ts:1:1 - error TS2352: Conversion of type 'undefined' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
> undefined as unknown as string
undefined

1 Answer 1

7

From docs on type assertion:

Type Assertion vs. Casting

The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However, type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

This means, foo as string will cause TypeScript compiler to treat foo as a string, even if it is not one. Specifically, undefined doesn't magically turn into not-undefined by TS compiler thinking it's a string.

However, TypeScript also knows that very few things that are not strings can be treated as a string sensibly, so you get an error (unless you trick it into forgetting what it was first).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.