Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

Commit 5e9ac4f

Browse files
Merge pull request #152 from Microsoft/typeAssertions
Added a small section on type assertions.
2 parents 87a2cb5 + a17123b commit 5e9ac4f

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

pages/Basic Types.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,8 +190,38 @@ 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 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 = (someValue as string).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+
193223
# A note about `let`
194224

195225
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.
196226
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

Comments
 (0)