nykon
nykon

Reputation: 654

Why do I have to explicitly set a default value of null to an optional parameter

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>'.

Upvotes: 0

Views: 602

Answers (1)

Tom
Tom

Reputation: 1188

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.

Upvotes: 1

Related Questions