File tree 2 files changed +27
-0
lines changed
src/07-other/01-type-cast-in-markup
2 files changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -352,6 +352,14 @@ This chapter shows how you can define events that a component emits.
352
352
how to wrap contexts with ` TypeScript `
353
353
** [ (TS-tipp #3 )] ( #3-wrap-functions-that-have-no-strong-typings ) **
354
354
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
+
355
363
<!-- ---------------------------------------------------------------------------------------------->
356
364
<!-- ---------------------------------------------------------------------------------------------->
357
365
Original file line number Diff line number Diff line change
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 >
You can’t perform that action at this time.
0 commit comments