You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Oct 12, 2022. It is now read-only.
Copy file name to clipboardExpand all lines: pages/Basic Types.md
+31-1Lines changed: 31 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -190,8 +190,38 @@ Declaring variables of type `void` is not useful because you can only assign `un
190
190
let unusable:void=undefined;
191
191
```
192
192
193
+
# Type assertions
194
+
195
+
Sometimes you'll end up in a situation where you'll know more about a value than TypeScript does.
196
+
Usually this will happen when you know the type of some entity could be more specific than its current type.
197
+
198
+
*Type assertions* are a way to tell the compiler "trust me, I know what I'm doing."
199
+
A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data.
200
+
It has has no runtime impact, and is used purely by the compiler.
201
+
TypeScript assumes that you, the programmer, have performed any special checks that you need.
202
+
203
+
Type assertions have two forms.
204
+
One is the "angle-bracket" syntax:
205
+
206
+
```ts
207
+
let someValue:any="this is a string";
208
+
209
+
let strLength:number= (<string>someValue).length;
210
+
```
211
+
212
+
And the other is the `as`-syntax:
213
+
214
+
```ts
215
+
let someValue:any="this is a string";
216
+
217
+
let strLength:number= (someValueasstring).length;
218
+
```
219
+
220
+
The two samples are equivalent.
221
+
Using one over the other is mostly a choice of preference; however, when using TypeScript with JSX, only `as`-style assertions are allowed.
222
+
193
223
# A note about `let`
194
224
195
225
You may've noticed that so far, we've been using the `let` keyword instead of JavaScript's `var` keyword which you might be more familiar with.
196
226
The `let` keyword is actually a newer JavaScript construct that TypeScript makes available.
197
-
We'll discuss the details later, but many common problems in JavaScript are alleviated by using `let`, so it's best practice to adopt it over using`var` whenever possible.
227
+
We'll discuss the details later, but many common problems in JavaScript are alleviated by using `let`, so you should use it instead of`var` whenever possible.
0 commit comments