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>'. 
4
  • site_url?: string is perfectly normal code and can work in many situations. How did it fail for you? Commented Jan 7, 2022 at 6:07
  • I updated the question with error message and calling details Commented Jan 7, 2022 at 6: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. Commented Jan 7, 2022 at 6:31
  • 1
    Just for clarity: i.redd.it/vy1n3ionqgg51.png :D Commented Jan 7, 2022 at 6:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

mh yes, true. so an object definition without content or no object definition at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.