TypeScript Type Casting
Type casting in TypeScript allows you to convert a variable from one type to another. This is useful when you know more about the type of a variable than TypeScript does. Type casting can be done using two syntaxes: the as
keyword and angle-bracket syntax.
Using the as
Keyword
The as
keyword is the recommended way to cast types in TypeScript. It is more readable and less likely to conflict with JSX syntax.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Using Angle-Bracket Syntax
Angle-bracket syntax is an alternative way to cast types. It is similar to the as
keyword but uses angle brackets.
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Type Assertions
Type assertions are a way to tell the TypeScript compiler to treat a variable as a specific type. This is useful when you know the type of a variable but TypeScript does not.
Example: Type Assertion with DOM Elements
When working with DOM elements, you may need to assert the type of an element to access its properties.
let inputElement = document.getElementById("myInput") as HTMLInputElement;
inputElement.value = "Hello, TypeScript!";
Non-Null Assertion Operator
The non-null assertion operator (!
) is used to tell the TypeScript compiler that a variable is not null
or undefined
. This is useful when you are sure that a variable is not null
or undefined
but TypeScript cannot infer it.
let someValue: string | null = "Hello, TypeScript!";
console.log(someValue!.length); // No error
Double Assertion
Double assertion is a technique to cast a variable to any
type first and then to the desired type. This is useful when you need to bypass type checking temporarily.
let someValue: any = "this is a string";
let strLength: number = (someValue as any as number).length;
Type Casting with Generics
Type casting can also be used with generics to specify the type of a variable.
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello, TypeScript!");
Conclusion
Type casting in TypeScript is a powerful feature that allows you to convert variables from one type to another. By using the as
keyword, angle-bracket syntax, type assertions, non-null assertion operator, double assertion, and type casting with generics, you can write more robust and maintainable code.
For more information, refer to the TypeScript documentation (opens in a new tab).