Skip to content

Commit 93d6bab

Browse files
author
Ivan Hofer
committed
add markup type cast example
closes #13
1 parent 7be3b12 commit 93d6bab

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,14 @@ This chapter shows how you can define events that a component emits.
352352
how to wrap contexts with `TypeScript`
353353
**[(TS-tipp #3)](#3-wrap-functions-that-have-no-strong-typings)**
354354

355+
356+
<!------------------------------------------------------------------------------------------------>
357+
358+
#### other
359+
360+
- **[type cast in markup](https://github.com/ivanhofer/sveltekit-typescript-showcase/tree/main/src/07-other/01-type-cast-in-markup)**:
361+
how to cast a type within the markup
362+
355363
<!------------------------------------------------------------------------------------------------>
356364
<!------------------------------------------------------------------------------------------------>
357365

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<script lang="ts">
2+
import type { Product } from '$models/product.model.js'
3+
4+
export let product: Product | undefined = undefined
5+
6+
// we make sure to always have a product, but TypeScript doesn't know that
7+
$: if (!product) {
8+
product = {
9+
name: 'Product 1',
10+
color: 'red',
11+
}
12+
}
13+
14+
const castProduct = (product: Product | undefined) => product as Product
15+
</script>
16+
17+
<!-- We can't use TypeScript syntax in our markup so we need to call
18+
a function that returns the object with the correct type -->
19+
<span>{castProduct(product).name}</span>

0 commit comments

Comments
 (0)