Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today, we’ll learn about TypeScript type conversions, where we can convert variables from one type to another.

There is no concept of conversion in JavaScript, because JavaScript is dynamically typed and we can assign different types of values to variables at any time. However, in TypeScript every variable has a type, and we can convert a variable from one type to another through type conversion.

In TypeScript, we convert types using the AS keyword or the <> operator.

useasKeyword type conversion

Suppose we have an HTML with an input element on it

<input type="text" value="hello">
Copy the code

We then use the querySelector() function to get the input element and print the value of the input element

let input = document.querySelector('input[type=text]');

console.log(input.value);
Copy the code

If you write code in the TS file in the editor, the code will find the following error

The error message is

It tells us that a variable of Element type does not have a value attribute. The error is reported because document.querySelector() returns an Element type.

Element does not have a value attribute. A: Conversion type

We know that the Element is an input Element, so the correct type is HTMLInputElement. We can use the AS keyword to convert Element type to HTMLInputElement.

let input = document.querySelector('input[type=text]') as HTMLInputElement;

console.log(input.value);
Copy the code

After modification, the error disappeared

As you can see, HTMLInputElement value is string when you hover over value.

Or you could write it the other way

let text = (input as HTMLInputElement).value;
Copy the code

Here we need to understand that HTMLInputElement inherits from HTMLElement and HTMLElement inherits from Element

So when we convert HTMLElement type to HTMLInputElement, the conversion is called a downward conversion. For example,

let el: HTMLElement;
el = new HTMLInputElement();
Copy the code

The el variable has type HTMLElement. We can assign an instance of type HTMLInputElement to it because HTMLInputElement is a subclass of type HTMLElement.

To summarize, use as to convert type syntax to

let a: typeA;
let b = a as typeB;
Copy the code

use<>Operator to perform type conversion

In addition to using the AS keyword, we can also use the <> operator for type conversions, for example

let input = <HTMLInputElement>document.querySelector('input[type=text]');

console.log(input.value);
Copy the code

To summarize, the syntax for conversion using the <> operator

let a: typeA;
let b = <typeB>a;
Copy the code

conclusion

Today we learned how to convert variables from one type to another in TypeScript using the as keyword or the <> operator.

If this article is helpful, wechat search [xiaoshuai’s programming notes], a little knowledge every day