Skip to content

Commit 97a0d96

Browse files
authored
docs: rm error code example and add more practical one and change type cast to type assertion.
1 parent c8170c3 commit 97a0d96

1 file changed

Lines changed: 22 additions & 8 deletions

File tree

packages/documentation/copy/en/javascript/JSDoc Reference.md

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,6 @@ var win;
7878

7979
/** @type {PromiseLike<string>} */
8080
var promisedString;
81-
82-
// You can specify an HTML Element with DOM properties
83-
/** @type {HTMLElement} */
84-
var myElement = document.querySelector(selector);
85-
element.dataset.myData = "";
8681
```
8782

8883
`@type` can specify a union type &mdash; for example, something can be either a string or a boolean.
@@ -160,10 +155,11 @@ var star;
160155
var question;
161156
```
162157

163-
#### Casts
158+
#### Type Assertions
159+
160+
TypeScript borrows cast syntax from Google Closure, using it as type assertions in JSDoc.
164161

165-
TypeScript borrows cast syntax from Google Closure.
166-
This lets you cast types to other types by adding a `@type` tag before any parenthesized expression.
162+
This lets you "cast" types to other types by adding a `@type` tag before any **parenthesized** expression like `as` keyword in TypeScript.
167163

168164
```js twoslash
169165
/**
@@ -173,12 +169,30 @@ var numberOrString = Math.random() < 0.5 ? "hello" : 100;
173169
var typeAssertedNumber = /** @type {number} */ (numberOrString);
174170
```
175171

172+
A more practical and common use case is to assign a specific HTML element type for a element.
173+
174+
Sometimes you will have information about the type of a value that TypeScript can’t know about.
175+
176+
For example, if you’re using `document.getElementById`, TypeScript only knows that this will return *some* kind of `HTMLElement`, but you might know that your page will always have an `HTMLCanvasElement` with a given ID.
177+
178+
In this situation, you can use a *type assertion* to specify a more specific type:
179+
180+
```js twoslash
181+
const myCanvas = /** @type {HTMLCanvasElement} */ (document.getElementById("main_canvas"));
182+
```
183+
176184
You can even cast to `const` just like TypeScript:
177185

178186
```js twoslash
179187
let one = /** @type {const} */(1);
180188
```
181189

190+
The type assertions can be nested:
191+
192+
```js twoslash
193+
const x = /** @type {number} */ (/** @type {unknown} */ ("hello"))
194+
```
195+
182196
#### Import types
183197

184198
You can import declarations from other files using import types.

0 commit comments

Comments
 (0)