1. What is type assertion?

Personal understanding type assertions fall into two main meanings:

(1) Interpreted cast

(2) A type assertion tells the compiler to stop checking for us, and trust me, it is the type.

2. Use

Methods a

let len = (<string>str).length;

// There are compatibility issues, which are not very compatible when using JSX
Copy the code

Mode 2 AS (Suggestion)

let len = (str as string).length;

Example 3.

For example, if we have a variable of type any, but we know that the variable holds a string, we can use type assertions to convert any to string, using a string method.

let str:any = 'it666';
// there is no.length prompt when it is any
let len = (str as string).length;
console.log(len);
Copy the code

Ts Introduction Notes Directory:

TS Introduction Note 1 – Type declarations for TS

TS Introduction Note 2 – TS interface further details

TS Introduction Note 3 — Function declarations in TS

TS Introduction Note 4 — Type Assertion for TS (Interpreted type conversions)

TS Introduction Note 5 – TS generics

TS Introduction Note 6 — Declaration files, modules, namespaces in TS

Record knowledge, transfer happiness ~

If my summary is helpful to you, please give me a thumbs up. Your encouragement is a great motivation for me to keep recording

If there are any errors in this article, please feel free to point them out in the comments