TS Casting
TypeScript casting allows you to override the inferred or declared type of a variable. This is helpful when you know more about the type of a value than TypeScript does. Casting is done using the as
keyword or angle bracket syntax.
Key Topics
Casting Basics
Casting helps you specify a more specific type for a variable when TypeScript cannot infer it. The as
keyword is commonly used for this purpose.
let input: unknown = "Hello, TypeScript!";
let strLength: number = (input as string).length;
console.log(strLength); // 17
Output
17
Explanation: The variable input
is cast to string
using the as
keyword, allowing access to string-specific properties like length
.
Angle Bracket Syntax
Angle bracket syntax is an alternative to as
for type casting. It is not supported in JSX files.
let someValue: any = "1234";
let numericValue: number = (parseInt(someValue));
console.log(numericValue); // 1234
Output
1234
Explanation: The value of someValue
is cast from any
to number
using angle brackets, enabling arithmetic operations.
Type Assertions
Type assertions are a way to tell TypeScript about the type of a value when you are confident of its correctness. They don’t perform runtime checks but help the compiler.
interface Employee {
id: number;
name: string;
}
let emp = {} as Employee;
emp.id = 1;
emp.name = "Alice";
console.log(emp); // { id: 1, name: "Alice" }
Output
{ id: 1, name: "Alice" }
Explanation: The emp
object is asserted to be of type Employee
, allowing TypeScript to understand its shape and provide type safety.
Key Takeaways
- as Keyword: Use
as
for explicit type casting. - Angle Brackets: An alternative casting syntax, but avoid in JSX files.
- Type Assertions: Inform TypeScript of a value's type without runtime validation.
- Best Practice: Use casting sparingly and only when you are sure about the type.