Skip to content

Commit 2342fd0

Browse files
Added a small section on type assertions.
1 parent 6ba6e27 commit 2342fd0

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

pages/Basic Types.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,8 +190,41 @@ Declaring variables of type `void` is not useful because you can only assign `un
190190
let unusable: void = undefined;
191191
```
192192

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 = (someValue as string).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+
193226
# A note about `let`
194227

195228
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.
196229
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

Comments
 (0)