Type assertions let you lie to TypeScript about what type a value is. This can be useful when you know more about a value than TypeScript does, or when you need a quick shortcut to keep the compiler quiet.
The as
Keyword
You can use the as
keyword to force TypeScript to convert a value to a different type.
ts
constelement =document .getElementById ("my-element") asHTMLDivElement ;console .log (element .innerText );
as
Has Limits
When using as
, the objects being compared need to be somewhat related to each other. It will error if you try to push it too far.
This occurs with primitives:
ts
constConversion of type 'number' 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.2352Conversion of type 'number' 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.str = 123 as string;
But also with objects that don't have any shared properties:
ts
typeDog = {bark : () => void;};constConversion of type '{ meow: () => void; }' to type 'Dog' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'bark' is missing in type '{ meow: () => void; }' but required in type 'Dog'.2352Conversion of type '{ meow: () => void; }' to type 'Dog' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'bark' is missing in type '{ meow: () => void; }' but required in type 'Dog'.dog = {meow : () => {console .log ("meow");},} asDog ;
The Double as
: as unknown as X
You can always force something to be of a certain type when you use as unknown as X
. This is because unknown
is assignable to any type, so you can use it to "reset" the type of a value.
ts
conststr = 123 as unknown as string;typeDog = {bark : () => void;};constdog = {meow : () => {console .log ("meow");},} as unknown asDog ;
This works because unknown
is the top type in TypeScript - so is somewhat related to all types. This also works with never
, the bottom type, and any
- a somewhat game-breaking type.
ts
conststr = 123 as any as string;conststr2 = 123 as never as string;
Share this TypeScript Concept with your friends