Everyday TypeScript: As
Welcome to the As lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
TypeScript's
askeyword lets us override the type of a variable or other value. It often shows up in code dealing withanyandunknownvalues.>
let aValue: unknown = 'hello';let aString = aValue as string;let length: number = aString.length;length;Result:
5
ascan help us when dealing with legacy JavaScript code. The example below builds a user object, starting with the empty object{}. This is fine in JavaScript, but when we port to TypeScript it causes a type error.>
const user = {};user.name = 'Amir';user.age = 36;user;Result:
If we're porting a large system from JavaScript to TypeScript, we probably want to avoid rewriting existing JavaScript code in simple cases like this. We'd rather add type definitions, leaving everything else unchanged. We can use
asto force the variable's type, letting the rest of the code stay the same.>
const user = {} as {name: string, age: number};user.name = 'Amir';user.age = 36;user;Result:
{name: 'Amir', age: 36}Let's take a closer look at what happened here. In our first example, TypeScript inferred the type of
user, an empty object, to be the anonymous object type{}. This caused an error when we tried to add the propertiesnameandageto the type{}.In our second example, we asked the compiler to treat our empty user object
as {name: string, age: number}, overriding its usual type checking. Notably, this would fail if we tried to assign this type directly.>
const user: {name: string, age: number} = {};user;Result:
By using
as, we were able to bypass the normal type checking, and forced the compiler to treat our user as an object typed{name: string, age: number}.This allowed us to assign the
nameandageproperties to the empty object. You can see how powerfulascan be!aslets us override the TypeScript compiler's normal types, so it can be a dangerous source of errors. We'll explore some common mistakes withasin a future lesson.