66
77* [ Introduction] ( #introduction )
88 * [ Default values] ( #default-values )
9+ * [ Nullable values] ( #nullable-values )
910 * [ Default and nullable] ( #default-and-nullable )
1011
1112<!-- - END -->
@@ -18,6 +19,7 @@ import dev.adamko.kxstsgen.*
1819
1920## Introduction
2021
22+ Some properties of a class are optional, or nullable, or both.
2123
2224### Default values
2325
@@ -26,32 +28,64 @@ it will be marked as optional using the `?:` notation.
2628
2729``` kotlin
2830@Serializable
29- class Color (val rgb : Int = 12345 )
31+ class Colour (val rgb : Int = 12345 )
3032
3133fun main () {
3234 val tsGenerator = KxsTsGenerator ()
33- println (tsGenerator.generate(Color .serializer()))
35+ println (tsGenerator.generate(Colour .serializer()))
3436}
3537```
3638
3739> You can get the full code [ here] ( ./knit/example/example-default-values-single-field-01.kt ) .
3840
3941``` typescript
40- export interface Color {
42+ export interface Colour {
4143 rgb? : number ;
4244}
4345```
4446
4547<!-- - TEST -->
4648
49+ ### Nullable values
50+
51+ Properties might be required, but the value can be nullable. In TypeScript that is represented with
52+ a type union that includes ` null ` .
53+
54+ ``` kotlin
55+ @Serializable
56+ class Colour (val rgb : Int? ) // 'rgb' is required, but the value can be null
57+
58+ fun main () {
59+ val tsGenerator = KxsTsGenerator ()
60+ println (tsGenerator.generate(Colour .serializer()))
61+ }
62+ ```
63+
64+ > You can get the full code [ here] ( ./knit/example/example-default-values-single-field-02.kt ) .
65+
66+ ``` typescript
67+ export interface Colour {
68+ rgb: number | null ;
69+ }
70+ ```
71+
72+ <!-- - TEST -->
73+
4774### Default and nullable
4875
76+ A property can be both nullable and optional, which gives four possible options.
77+
4978``` kotlin
5079@Serializable
5180data class ContactDetails (
81+ // nullable: ❌, optional: ❌
82+ val name : String ,
83+ // nullable: ✅, optional: ❌
5284 val email : String? ,
85+ // nullable: ❌, optional: ✅
86+ val active : Boolean = true ,
87+ // nullable: ✅, optional: ✅
5388 val phoneNumber : String? = null ,
54- val active : Boolean? = true ,
5589)
5690
5791fun main () {
@@ -62,15 +96,12 @@ fun main() {
6296
6397> You can get the full code [ here] ( ./knit/example/example-default-values-primitive-fields-01.kt ) .
6498
65- Email has no default, so it is not marked as optional.
66-
67- Phone number and is nullable, and has a default, so i
68-
6999``` typescript
70100export interface ContactDetails {
101+ name: string ;
71102 email: string | null ;
103+ active? : boolean ;
72104 phoneNumber? : string | null ;
73- active? : boolean | null ;
74105}
75106```
76107
0 commit comments