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
Copy file name to clipboardExpand all lines: pages/Basic Types.md
+34-1Lines changed: 34 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -190,8 +190,41 @@ 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 a little better than TypeScript about the type of something.
196
+
Usually, this will happen when you know the type of a value is 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 where some languages might perform some special checking or restructuring of data, a type assertion has no runtime impact.
200
+
The assumption is that you, the programmer, have performed any special checks that you need.
201
+
202
+
Type assertions have two forms.
203
+
One is the "angle-bracket" syntax:
204
+
205
+
```ts
206
+
let someValue:any;
207
+
208
+
// ...
209
+
210
+
let strLength:number= (<string>someValue).length;
211
+
```
212
+
213
+
And the other is the `as`-syntax:
214
+
215
+
```ts
216
+
let someValue:any;
217
+
218
+
// ...
219
+
220
+
let strLength:number= (someValueasstring).length;
221
+
```
222
+
223
+
The two samples are equivalent.
224
+
Using one over the other is mostly a choice of preference; however, when using TypeScript with JSX, only `as`-style assertions are allowed.
225
+
193
226
# A note about `let`
194
227
195
228
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
229
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.
230
+
We'll discuss the details later, but many common problems in JavaScript are alleviated by using `let`, so it's a best practice to adopt it over using `var` whenever possible.
0 commit comments