0

I'm a Kotlin developer and touched some typescript lately. I ran into a type issue that originated in

site_url?: string
site_domain?: string

and was solved with these changes:

site_url: string | null
site_domain: string | null

I read into it and ? means that the field is optional. If it is optional, it can be null. Is the issue that I did not set a default value null and wanted to do it implicitly? Why do we need to specify a 'default value' of null if the parameter is marked as optional?

I also had to change the method from

export const doSomething = async (domain: string): Promise<Something> => {

to

export const doSomething = async (domain: string | null): Promise<Something> => {

The error that was, for me, really hard to debug was:

Type error: Argument of type '(domain: string) => Promise<Something>' is not assignable to parameter of type '(value: string | undefined, index: number, array: (string | undefined)[]) => Promise<Something>'.
nykon
  • 504
  • 4
  • 18
  • `site_url?: string` is perfectly normal code and can work in many situations. How did it fail for you? – CertainPerformance Jan 07 '22 at 06:07
  • I updated the question with error message and calling details – nykon Jan 07 '22 at 06:11
  • 2
    "*If it is optional, it can be null.*" no, optional means it can be missing (or `undefined`) but not `null`. Assuming you have `strictNullChecks` enabled. With the strict rule enabled, you cannot assign `null` to something marked optional but not marked that it can receive a `null`. – VLAZ Jan 07 '22 at 06:31
  • 1
    Just for clarity: https://i.redd.it/vy1n3ionqgg51.png :D – GOTO 0 Jan 07 '22 at 06:36

1 Answers1

1

Optional parameters in TS/JS give a value of undefined rather than null when accessed. You can also explicitly pass undefined as a value.

This answer goes into detail on the differences.

If you need to use null specifically for an external typed library, you would need to catch undefined and set it to null.

Tom
  • 1,158
  • 6
  • 19