The as Keyword in TypeScript
The as
keyword can be used in these cases when the type of the object is known though unknown to the compiler to perform a Type Assertion to associate the required type to the object.
It is a TypeScript construct, and it will not affect the transcompile JavaScript code.
Use the as
Keyword to Cast Types in TypeScript
The as
keyword can cast a type that can be a more specific or less specific version of the expected type.
interface User {
name : string
id : number
}
function getUser(){
let username : string = "Geralt";
return {
name : username,
id : 1
};
}
let user = getUser() as User;
In this way, we force the compiler to associate the user
object with the type User
for more robust auto-completion and suggestions resulting in a better development experience.
Another use case is initializing arrays or empty objects to be filled in later.
let user : User = {} as User;
let userArray : User[] = [] as User[];
Without the as
keyword, TypeScript will complain about {}
or []
not matching types or missing some properties.
Use the as
Keyword in Type Predicates in TypeScript
The as
keyword is in type predicates. Type predicates are used as type guards on untyped objects or objects with weak types, such as the union of two or more types.
interface Dog {
bark() : void;
}
interface Cat {
meow() : void;
}
function DogOrCat() : Dog | Cat {
let dog : Dog = {
bark(){
console.log("bark");
}
};
return dog;
}
function isDog( animal : Dog | Cat ) : animal is Dog {
return ( animal as Dog).bark !== undefined;
}
let animal = DogOrCat();
if (isDog(animal)){
(animal as Dog).bark()
}
The animal is Dog
is used as a type predicate.
In this way, the as
keyword can be used as type guards and other ways, such as the in
keyboard.