2

I want a function to return either an object or null.

Here is how I handle it today:

export interface MyObject {
    id: string
}

function test(id) : MyObject | null {
    if (!id) {
        return null;
    }

    return {
        id: id
    }
}

Is this best practice?

I would prefer to make the interface nullable rather than returning MyObject | null.

But I don't know if that is possible.

1

3 Answers 3

2

Is this best practice?

It's just fine. Everybody does that (or with undefined).

I would prefer to make the interface nullable rather than returning MyObject | null.

You can do:

export type NullableObject = null | {
  id: string
}

It is uncommon but fine too.

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

Comments

1

In Typescript, null and undefined are part of the domains of all types, unless strict null checks are enabled. In my opinion, explicitly declaring nulls is a much better practice than having them everywhere implicitly, but in the real world it is often not realistic to enable strict mode when interoperating with library code that isn't designed for it.

1 Comment

Do you think I am already following best practice or is there a better way to explicitly declare nulls?
0

This should handle null case too (if --strictFunctionTypes compiler option is off)

function test(id) : MyObject {
    if (!id) {
        return null;
    }

    return {
        id: id
    }
}

2 Comments

Thanks! However, I don't think I want to turn that off yet. I don't know TypeScript well enough to start turning things off.
@user1283776 more info about your question is here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.