← Concepts

Type Assertions

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.

const element = document.getElementById(
  "my-element"
) as HTMLDivElement;

console.log(element.innerText);
(property) HTMLElement.innerText: string

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:

const str = 123 as string;
Conversion 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.2352
Conversion 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.

But also with objects that don't have any shared properties:

type Dog = {
  bark: () => void;
};

const dog = {
Conversion 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'.2352
Conversion 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'. meow: () => { console.log("meow"); }, } as Dog;

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.

const str = 123 as unknown as string;

type Dog = {
  bark: () => void;
};

const dog = {
  meow: () => {
    console.log("meow");
  },
} as unknown as Dog;

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.

const str = 123 as any as string;
const str2 = 123 as never as string;

Share this TypeScript Concept with your friends